Validation of global variables and entry points

This commit is contained in:
Dzmitry Malyshau authored and Dzmitry Malyshau committed 2020-09-17 16:12:56 -04:00
1 parent 1c3f4513de
commit 14feb9ac01
6 files changed
+333 -39

No files matched your search

+1 -1
View File
@@ -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,
},
);
+23 -13
View File
@@ -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<crate::Type>), 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<crate::Type>,
) -> Result<(Handle<crate::Type>, crate::StorageAccess), Error<'a>> {
) -> Result<Handle<crate::Type>, 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(';'))?;
}
+306 -23
View File
@@ -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<crate::Type>),
#[error("Expression type can't be resolved")]
Resolve(Handle<crate::Function>, 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::GlobalVariable>, crate::GlobalUse),
#[error("Bindings for {0:?} conflict with other global variables")]
BindingCollision(Handle<crate::GlobalVariable>),
#[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<crate::Type>),
#[error("Global variable {0:?} is invalid: {1:?}")]
GlobalVariable(Handle<crate::GlobalVariable>, GlobalVariableError),
#[error("Function {0:?} is invalid: {1:?}")]
Function(Handle<crate::Function>, 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<crate::Type>,
) -> 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(())
+1 -1
View File
@@ -67,7 +67,7 @@ type Particles = struct {
[[builtin(global_invocation_id)]] var gl_GlobalInvocationID : vec3<u32>;
# 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) {
+1 -1
View File
@@ -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: [],
+1
View File
@@ -9,6 +9,7 @@ fn test_rosetta(dir_name: &str) {
{
use naga::back::*;
let module = ron::de::from_str::<naga::Module>(&expected).unwrap();
naga::proc::Validator::new().validate(&module).unwrap();
#[cfg(feature = "spv-out")]
{