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