Commit Graph

2381 Commits

Author SHA1 Message Date
Chris Oattes
e803fe6717
Don't convert struct members to half (#5201) 2023-05-08 12:14:42 -04:00
Steven Perron
8993f9f52f
Apply scalar replacement on vars with Pointer decorations (#5208)
We want to be able to apply scalar replacement on variables that have
the AliasPointer and RestrictPointer decorations.

This exposed a bug that needs to be fixed as well.

Scalar replacement sometimes uses the type manager to get the type id for the
variables it is creating. The variable type is a pointer to a pointee
type. Currently, scalar replacement uses the type manager when only if
the pointee type has to be unique in the module. This is done to try to avoid the case where two type hash to the same
value in the type manager, and it returns the wrong one.

However, this check is not the correct check. Pointer types still have to be
unique in the spir-v module. However, two unique pointer types can hash
to the same value if their pointee types are isomorphic. For example,

%s1 = OpTypeStruct %int
%s2 = OpTypeStruct %int
; %p1 and %p2 will hash to the same value even though they are still
; considered "unique".
%p1 = OpTypePointer Function %s1
%p2 = OpTypePointer Function %s2
To fix this, we now use FindPointerToType, and we modified TypeManager::IsUnique to refer to the whether or not a type will hash to a unique value and say that pointers are not unique.

Fixes #5196
2023-05-08 09:39:14 -04:00
Jeremy Gebben
0ce36ad785
instrument: Add set and binding to bindless error records (#5204)
Add set and binding fields to the error records so that it is
easier for users to figure out which descriptor caused an error.
2023-05-01 14:23:30 -04:00
Jeremy Gebben
d4c0abdcad
instrument: Change descriptor state storage format (#5178)
Split per-DescriptorSet state into separate memory blocks
which are accessed via an array of buffer device addresses.
This is being done to make it easier to update state for a
single DescriptorSet without rebuilding the old giant flat
buffer.

The new data format is documented as comments in
include/spirv-tools/instrument.hpp
2023-04-26 14:28:01 -06:00
Ben Clayton
bec566a32b
opt: Fix null deref in OpMatrixTimesVector and OpVectorTimesMatrix (#5199)
When some (not all) of the matrix columns are OpConstantNull
2023-04-18 14:58:12 -04:00
janharaldfredriksen-arm
6f276e05cc
Add support for SPV_EXT_shader_tile_image (#5188)
* Update DEPS file to pull in header changes for SPV_EXT_shader_tile_image
2023-04-13 16:58:00 -04:00
James Price
1877a7f909
Fix vector OpConstantComposite type validation (#5191)
The constituent types much fully match, not just the opcode.
2023-04-13 12:50:16 -04:00
LDeakin
dd03c1fca4
Fix LICMPass (#5087)
Do not move loads out of the loop unless the memory is readonly.

Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/5075
2023-04-05 11:48:14 -04:00
Steven Perron
a0fcd06f8f
Add Vulkan memory model to allow lists (#5173)
Fixes #5086
2023-03-28 16:57:45 -04:00
Spencer Fricke
d8a8af8e6d
spirv-val: Remove unused includes and code (#5176) 2023-03-28 14:18:19 -04:00
Spencer Fricke
fa69b09cff
spirv-opt: Remove unused includes and code (#5177) 2023-03-28 12:40:30 -04:00
Steven Perron
d24a39a7f0
Do not remove control barrier after spv1.3 (#5174)
The control barrier instruction was allowed in a limiteted set of shader types.
Part of the HLSL legalization, we use to remove the instructions when it was is
a shader in which it was not allowed. As of spv1.3 that restriction is not long
there.

This change modifies replaced invalid opc to no longer remove it.

Fixes #4999.
2023-03-27 11:04:40 -04:00
alan-baker
9fbe1738ba
Update SPIRV-Headers deps (#5170)
* Update test expectations to account for simplified enables
* Don't clone spirv-headers twice for the smoketest
2023-03-23 13:00:42 -04:00
Nathan Gauër
5f4e694e10
Implement source extraction logic for spirv-objdump (#5150)
* dump: add ability to extract HLSL from module

Only adds the code to extract the source from the module. The extracted files are written to the given directory.
Android NDK21 has C++17 support, but no std::filesystem support. (NDK22). As for now, the tool is not built on Android.
Might be something to revisit is the need to have this tool on Android arises.
2023-03-22 23:57:18 +01:00
Spencer Fricke
8e6563b913
spirv-val: Label new Vulkan VUID 07951 (#5154) 2023-03-18 01:01:50 +00:00
Nathan Gauër
fcd53c8ed2
Add spirv-dump tool (#5146)
* dump: add tool skeleton.

This tool aims to be used a bit like objdump (hence the name).
Allowing the user to dump some info from a spirv-binary.

* add test structure for spirv-dump

* add spirv-dump to bazel build file

* fix licenses

* fix compilation with ubsan

* remove fdiagnostics

* rename dump to objdump

* move tests to test/tools

* rename dump to objdump for bazel
2023-03-13 16:39:42 +01:00
Laura Hermanns
bd83b772c3
Fix operand index out of bounds when folding OpCompositeExtract. (#5107)
GetExtractOperandsForElementOfCompositeConstruct() states "Returns the
empty vector if |result_index| is out-of-bounds", but violates that
contract for non-vector result types.
2023-03-03 15:52:49 +00:00
Nathan Gauër
8cee461986
tools: add uint32_t flags parsing (#5131)
* tools: add uint32_t flags parsing

This will be required to refactorize other tools.
2023-03-02 15:16:32 +01:00
Nathan Gauër
2e0f4b52c9
tools: refactorize tools flags parsing. (#5111)
* tools: refactorize tools flags parsing.

Each SPIR-V tool was handing their own flag parsing. This PR
adds a new flag parsing utility that should be flexible enough
for our usage, but generic enough so it can be shared across tools while
remaining simple to use.

* cfg: replace cfg option parsing with the new one.

* change spirv-dis parsing + title + summary

* clang format

* flags: fix static init fiasco & remove help

Static initialization order is important, and was
working just by sheer luck.

Also removing the help generation tooling. It's less flexible than the
hand-written string, and making it as-good and as-flexible brings too
much complexity.

* review feedback
2023-02-27 18:45:14 +01:00
alan-baker
5d2bc6f064
Fix removal of dependent non-semantic instructions (#5122)
Fixes #5121

* If the non-semantic info instructions depended on other moved
  instructions the def/use manager would get corrupted.
2023-02-24 01:10:35 +00:00
Nathan Gauër
b84c86f718
libspirv.cpp: adds c++ api for spvBinaryParse (#5109)
This commit adds a C++ wrapper above the current spvBinaryParse
function. I tried to match it 1:1, except for 2 things:
 - std::function<>& are used. No more function pointers, allowing
   context capture.
 - spv_result_t replaced with a boolean, to match other C++ apis.

Callbacks still return a spv_result_t because the underlying implem
relies on that. The convertion from spv_result_t to boolean is only done
at the boundary.

Signed-off-by: Nathan Gauër <brioche@google.com>
2023-02-14 14:08:20 -05:00
Caio Oliveira
0ce2bc4ce0
spirv-val: Conditional Branch without an exit is invalid in loop header (#5069)
* Update fuzz tests to not use invalid combinations of LoopMerge + BranchConditional

New IDs were selected to make clear the transformation being done here, instead
of reordering all IDs in between or refactoring the SPIR-V in the test.

* spirv-val: Conditional Branch without an exit is invalid in loop header

From 2.16.2, for CFG:

    Selections must be structured. That is, an OpSelectionMerge
    instruction is required to precede:

    - an OpSwitch instruction

    - an OpBranchConditional instruction that has different True Label
      and False Label operands where neither are declared merge blocks
      or Continue Targets.
2023-02-06 10:31:47 -05:00
Laura Hermanns
cac9a5a3ee
Fix null pointer in FoldInsertWithConstants. (#5093)
* Fix null pointer in FoldInsertWithConstants.

Struct types are not supported in constant folding yet.

* Added 'Test case 16' to fold_test.

Tests OpCompositeInsert not to be folded on a struct type.
2023-02-03 15:03:15 +00:00
Maciej
fd1e650cfe
Validate decoration of structs with RuntimeArray (#5094)
Contributes to https://github.com/KhronosGroup/glslang/issues/2439

* When OpTypeStruct is used in Vulkan env and its last member
  is a RuntimeArray, check if the struct is decorated with
  Block or BufferBlock, as required by VUID-...-04680.
2023-02-03 08:58:51 -05:00
Jeremy Gebben
5890763734
instrument: Clean up generation code (#5090)
-Make more use of InstructionBuilder instruction helper methods
-Use MakeUnique<>() rather than new
-Add InstrumentPass::GenReadFunctionCall() which optimizes function
calls in a loop with constant arguments and no side effects.

This is a prepatory change for future work on the instrumentation
code which will add more generated functions.
2023-02-03 00:39:09 +00:00
Daniel Story
0994ca45b6
Add C interface for Optimizer (#5030) 2023-02-01 13:58:52 +00:00
alan-baker
b230a7c7d1
Validate operand type before operating on it (#5092)
Fixes https://crbug.com/oss-fuzz/52921

* Validate the data operand of OpBitCount before trying to get its
  dimension
2023-01-31 15:40:22 -05:00
Steven Perron
5db6c38e65
Revert "spirv-val: Initial SPV_EXT_mesh_shader builtins (#5080)" (#5084)
This reverts commit f0b900ed9a.
2023-01-24 19:51:39 +00:00
Spencer Fricke
f0b900ed9a
spirv-val: Initial SPV_EXT_mesh_shader builtins (#5080) 2023-01-23 14:30:45 +00:00
Jeremy Gebben
ba4c9fe534
Instrument: Fix bindless checking for BufferDeviceAddress (#5049)
Avoid using OpConstantNull with types that do not allow it.

Update existing tests for slight changes in code generation.

Add new tests based on the Vulkan Validation layer test case
that exposed this problem.
2023-01-16 20:57:37 +00:00
alan-baker
7e8813bb4c
Validate version 5 of clspv reflection (#5050)
* Validate version 5 of clspv reflection

* Add validation for instructions in versions 2 through 5
* Change the instruction reported for remaining indices on an access
  chain to the access chain itself for clarity

* update spirv-headers
2023-01-11 16:58:53 -05:00
Caio Oliveira
f62e121b0d
spirv-val: Use more specific term 'switch header' in error message (#5048)
* spirv-val: Add tests for OpSwitch directly breaking/continuing outer loop

These are not valid, tests verify the validator catches the issue.
2023-01-09 18:39:02 -05:00
Rafael Marinheiro
c5d2316430
Enforce layering_check in Bazel build rules. (#5032)
* Enforce layering_check in Bazel build rules.

Enforcing layering_check ensures that the Build targets do not rely on
transitive dependencies. See
https://github.com/bazelbuild/bazel/pull/11440 for a detailed
description of the feature.

We also do a style pass on the build files, ensuring that common linters
are happy with it.

* Add .bazelversion file and fix build_defs.bzl.

We fix build_defs.bzl to work on Bazel 5.0.0.
2022-12-20 10:54:46 -05:00
David Neto
2937538210
Fix undef behaviour in hex float parsing (#5025)
When the parser saw more significant hex digits than fit in
the target type, it would compute a nonsensical shift amount, resulting
in undefined behaviour.

Now, drop the excess bits, effectively truncating the significand.

Also guard against overflow of the exponent in the extraordinary (and untested)
case where we see more than, for example, 2**(32-4+1) significant hex digits
for a 32-bit float, or 2**(16-4+1) significant hex digits for a 16-bit
float.

Also guard against overflow of the indexing counting the number of
significant bits.  When that would occur silently drop any further
significant bits.  (Untested)

Avoid hex floats in C++ code. It's a C++17 feature.

Fixes: #4724
2022-12-19 15:46:57 -05:00
Greg Fischer
f64a4b64b7
[spirv-opt] Clone names for new struct in EliminateIODeadComponents (#5016) 2022-12-19 10:20:44 -07:00
David Neto
cc81529f4b
Test operator overloads for SPIR-V C++ mask enums (#5021)
Updates SPIRV-Headers in DEPS
2022-12-16 11:17:39 -05:00
alan-baker
5a78d798f7
Fix layout validation (#5015)
* Fix layout validation

Fixes #5010

* Unless scalar block layout is enabled, no member can reside at an
  offset between the end of the previous member that is a struct or
  array and the next multiple of that alignment

* Remove a dead if that was introduced

Co-authored-by: David Neto <dneto@google.com>
2022-12-15 21:38:09 -05:00
Pankaj Mistry
6b2318aec8
Fix for bug https://github.com/KhronosGroup/SPIRV-Tools/issues/5017 (#5019)
open_quote value becomes npos when it fails to find '\'' and then is used to
compute the string length for writing to result. This causes crash in win32 builds of the test.
2022-12-15 21:13:12 -05:00
alan-baker
235182cfee
Fix use of invalid analysis (#5013)
Fixes https://crbug.com/1395415

* Block merging needed to invalid structured cfg analysis
2022-12-12 10:49:59 -05:00
alan-baker
9c6a925c87
Fix infinite loop in validator (#5006)
Fixes https://crbug.com/oss-fuzz/53510

* Fix infinite loop that could occur in structured cfg validation due to
  an invalid cfg
2022-12-06 11:22:33 -05:00
Spencer Fricke
7b8f00f00a
spirv-opt: Fix OpCompositeInsert with Null Constant (#5008)
* spirv-opt: Unify GetConstId function names

* spirv-opt: Fix OpCompositeInsert with Null Constant

* spirv-opt: Improve GetNullCompositeConstant description
2022-12-06 09:00:10 -05:00
Cassandra Beckley
40f5bf59c6
Revert "spirv-val: Multiple interface var with same SC (#4969)" (#5009)
This reverts commit 996d4c021f. This
commit is likely good, but it causes a failure in DXC tests. Will
un-revert once we fix the issue in DXC.
2022-12-05 12:31:01 -08:00
Greg Fischer
00018e58af
Change EliminateDeadInputComponentsPass to EliminateDeadIOComponentsPass (#4997)
To reflect processing of both Input and Output variables.

Also renamed files as needed.
2022-11-25 16:48:13 -07:00
alelenv
f33d152400
Add validation support for SPV_NV_shader_invocation_reorder. (#4979)
Co-authored-by: Pankaj Mistry <pmistry@nvidia.com>
2022-11-24 09:50:45 -05:00
Spencer Fricke
597631b693
spirv-opt: Handle null CompositeInsert (#4998)
Fixes #4996
2022-11-24 08:38:12 -05:00
Greg Fischer
81ec2aaa0e
Add option to ADCE to remove output variables from interface. (#4994)
This can cause interface incompatibility and should only be done
if ADCE has been applied to the following shader in the pipeline.
For this reason this capability is not available through the CLI
but rather only non-default through the API. This functionality is
intended as part of a larger cross-shader dead code elimination
sequence.
2022-11-23 10:48:58 -07:00
Greg Fischer
46ca66e699
Add support for tesc, tese and geom to EliminateDead*Components (#4990) 2022-11-18 15:08:18 -07:00
Greg Fischer
8ea3ae6be2
Split EliminateDeadInputComponents into safe and unsafe versions. (#4984)
Safe version will only optimize vertex shaders. All other shaders will
succeed without change.

Change --eliminate-dead-input-components to use new safe version.

Unsafe version (allowing non-vertex shaders) currently only available
through API. Should only be used in combination with other optimizations
to keep interfaces consistent. See optimizer.hpp for more details.
2022-11-14 11:44:26 -07:00
Jeremy Gebben
68e8327f29
Instrument: Change output buffer offset definitions (#4961)
Add a flags field at the first offset within this buffer.
Define flags to allow buffer OOB checking to be enabled or
disabled at run time. This is to support VK_EXT_pipeline_robustnes.
2022-11-10 12:35:18 -05:00
Spencer Fricke
996d4c021f
spirv-val: Multiple interface var with same SC (#4969)
* spirv-val: Multiple interface var with same SC

* spirv-val: Use C style headers
2022-11-10 12:32:58 -05:00
Greg Fischer
525bc38062
Add pass to eliminate dead output components (#4982)
This pass eliminates components of output variables that are not stored
to. Currently this just eliminates trailing components of arrays and
structs, all of which are dead.

WARNING: This pass is not designed to be a standalone pass as it can
cause interface incompatibiliies with the following shader in the
pipeline. See the comment in optimizer.hpp for best usage. This pass is
currently available only through the API; it is not available in the CLI.

This commit also fixes a bug in CreateDecoration() which is part of the
system of generating SPIR-V from the Type manager.
2022-11-08 10:45:32 -07:00
Spencer Fricke
54d4e77fa5
spirv-opt: Add const folding for CompositeInsert (#4943)
* spirv-opt: Add const folding pass for CompositeInsert

* spirv-opt: Fix anas stack-use-after-scope
2022-11-08 10:50:42 -05:00
Spencer Fricke
a5e766b2b4
spirv-val: Add VUID label for 07703 (#4980) 2022-11-06 19:05:25 -05:00
alan-baker
d35a78db57
Switch SPIRV-Tools to use spirv.hpp11 internally (#4981)
Fixes #4960

* Switches to using enum classes with an underlying type to avoid
  undefined behaviour
2022-11-04 17:27:10 -04:00
Greg Fischer
c8e1588cfa
Add passes to eliminate dead output stores (#4970)
This adds two passes to accomplish this: one pass to analyze a shader
to determine the input slots that are live. The second pass is run on
the preceding shader to eliminate any stores to output slots that are
not consumed by the following shader.

These passes support vert, tesc, tese, geom, and frag shaders.

These passes are currently only available through the API.

These passes together with dead code elimination, and elimination of
dead input and output components and variables (WIP), will allow users
to do dead code elimination across shader boundaries.
2022-11-02 11:23:25 -06:00
alan-baker
a52de681dd
Prevent eliminating case constructs in block merging (#4976)
Fixes #4918

* Prevent block merging from producing an invalid case construct by
  merging a switch target/default with another construct's merge or
  continue block
* This is to satisfy the structural dominance requirement between the
  switch header and the case constructs
2022-10-28 14:13:20 -04:00
alan-baker
4563d90934
Only validate full layout in Vulkan environments (#4972)
Fixes #4671
Fixes https://crbug.com/oss-fuzz/43265

* Only validate full layout in a vulkan environment
  * Universal validation still checks that the right decorations are
    present, but the values are only considered for vulkan
* One exception is that invalid overlaps are only checked for vulkan
  * This is a pragmatic choice as SPIR-V doesn't define the size of
    types so the amount of universal checking would be quite limited
* Removed redundant check for GLSLShared and GLSLPacked decorations
  * Should never have been validated as part of universal validation

* make conditionals independent
2022-10-28 11:52:28 -04:00
Spencer Fricke
9f3a4afae4
spirv-val: Label new Vulkan OpPtrAccessChain VUs (#4975) 2022-10-27 10:10:27 -04:00
alan-baker
7326b967a5
Prevent null pointer from being dereferenced (#4971)
Fixes https://crbug.com/oss-fuzz/48553

* Assign a reflexive dominator if no other dominator can be found using
  forward traversals
  * This prevents a null dereference of a pointer in the sorting of the
    output
2022-10-24 15:16:33 -04:00
Spencer Fricke
0ebf830572
spirv-val: Add OpPtrAccessChain Base checks (#4965) 2022-10-24 12:45:08 -04:00
Spencer Fricke
eb113f0fdf
spirv-val: Improve PR 4831 error message (#4968) 2022-10-20 10:51:43 -04:00
Spencer Fricke
ecd5b9c167
spirv-val: Add remaining Component decoration validation (#4966) 2022-10-17 16:54:39 -04:00
gmitrano-unity
1cecf91701
Support Narrow Types in BitCast Folding Rule (#4941)
* Support Narrow Types in BitCast Folding Rule

This change adds support for narrow types in the BitCastScalarOrVector
folding rule. According to Section 2.2.1 of the SPIR-V spec, types that
are narrower than 32 bits are automatically either sign extended, or
zero extended depending on the type. With that guaranteed, we should
be able to use the first 32-bit word of any narrow type for the folding
logic without performing any special conversions.

In order to reduce code duplication, this change moves the
GetU32BitValue and GetU64BitValue functions from IntConstant to
ScalarConstant. Without this move, we would have needed an identical
version of GetU32BitValue on FloatConstant.

* Add Tests for 16-bit BitCast Folding

This change adds several new test cases to the
IntegerInstructionFoldingTest which trigger the 16-bit BitCast logic.
The logic for half types was also added to the integer case since we
can't easily validate half float types in C++ code. It's easier to
validate them as unsigned integers instead. Pllus this also allows us
to verify the SPIR-V constant sign extension logic too.

* Add 8-Bit Folding Test Cases

This change adds a couple more test cases to the integer instruction
folding test suite in order to ensure that the BitCast logic also
works correctly with the Int8 shader capability.
2022-10-06 10:35:18 -04:00
Kévin Petit
a6e6454ef2
spirv-val: Add SPV_ARM_core_builtins validation (#4958)
Signed-off-by: Kevin Petit <kevin.petit@arm.com>
Change-Id: If1680a823aea9662d44def1ec6fe6ac334c00574

Signed-off-by: Kevin Petit <kevin.petit@arm.com>
2022-10-05 22:47:10 -04:00
Shahbaz Youssefi
4dbc66380d
spirv-val: Use ostringstream in id validation tests (#4956)
Proved to be marginally faster than appending to string.
2022-09-30 15:24:48 -04:00
Shahbaz Youssefi
07d361b675
spirv-val: Add an option to use friendly names or not (#4951)
The always-friendly messages make it harder to debug when the
disassembly is later generated without friendly names.

Additionally, the friendly-name-mapper is slow.  Disabling it improves
performance of an ANGLE test that creates numerous shaders by ~5%.
2022-09-30 12:22:00 -04:00
Shahbaz Youssefi
3ec6b3698e
spirv-val: Consistently quote ids in messages (#4950)
Half the messages used to output 'id[%name]' and half id[%name].  With
this change, all messages consistently output 'id[%name]'.  Some typos
are also fixed in the process.
2022-09-29 10:03:49 +02:00
Spencer Fricke
b53d7a8aff
spirv-val: Add initial SPV_EXT_mesh_shader validation (#4924)
* Move TaskEXT check to OpEmitMeshTasksEXT

* Add MeshNV for Execution Model alias
2022-09-23 11:06:46 -04:00
Greg Fischer
265b455c99
Fix CreatDebugInlinedAt to not invoke def_use_mgr (#4939) 2022-09-23 08:45:32 -04:00
Spencer Fricke
ddbee48f85
spirv-opt: Fix stacked CompositeExtract constant folds (#4932)
This was spotted in the Validation Layers where OpSpecConstantOp %x CompositeExtract %y 0 was being folded to a constant, but anything that was using it wasn't recognizing it as a constant, the simple fix was to add a const_mgr->MapInst(new_const_inst); so the next instruction knew it was a const
2022-09-23 08:45:11 -04:00
Ricardo Garcia
aeb1c64d4a
spirv-val: Make it legal to use arrays of ray queries (#4938)
Private arrays of ray queries are legal to use. Several CTS tests check
they work properly but were being rejected by spirv-val.
2022-09-21 15:27:36 -04:00
Spencer Fricke
0c4ce11b4a
spirv-val: Update VUID from 1.3.228 Vulkan spec (#4936)
Co-authored-by: alan-baker <alanbaker@google.com>
2022-09-16 14:51:36 -04:00
Spencer Fricke
5f4ce362ad
spirv-val: Label VUID 07290 (#4927) 2022-09-16 14:05:40 -04:00
Spencer Fricke
8422d8a44b
spirv-val: Label ShaderRecordBufferKHR VUID (#4926) 2022-09-16 14:05:23 -04:00
Spencer Fricke
c3f844aec4
spirv-val: Test file suffix consistency (#4925) 2022-09-16 14:05:07 -04:00
Greg Fischer
272e4b3d07
Fix missing and incorrect DebugValues (#4929)
Specificially, fixes DebugValues coming out of
eliminate-local-single-store and eliminate-local-multi-store AKA SSA
rewrite.
2022-09-13 14:41:07 +00:00
Jeremy Hayes
fb27bbf307
Fix DebugInlinedAt Line operand (#4928)
Line instructions may be OpLine or DebugLine. This commit adds support
for DebugLine.
2022-09-09 13:56:35 -04:00
Spencer Fricke
f5b27b6513
spirv-diff: Allow no SpecId (#4904) 2022-09-07 15:14:26 -04:00
Spencer Fricke
59cf5b1346
spirv-val: consider OpEmitMeshTasksEXT a terminator instruction (#4923) 2022-09-07 15:12:07 -04:00
Spencer Fricke
934a059787
spirv-val: Label Builtin Array Test VUIDs (#4921) 2022-09-07 10:29:38 -04:00
Pankaj Mistry
4c456f7da6
Implement tool changes for SPV_EXT_mesh_shader. (#4915)
- Added validation rule to support EXT_mesh_shader from SPIRV 1.4 onwards
2022-09-01 20:36:15 -04:00
jeremyg-lunarg
33113abf45
Instrument: Add OpNames to generated functions and variables (#4873)
Add name annotations to the generated instrumentation code to
make it easier to understand. Example spirv-cross output:

    vec4 _140;
    if (0u < inst_bindless_direct_read_4(0u, 0u, 1u, uint(_19)))
    {
        _140 = texture(textures[nonuniformEXT(_19)], inUV);
    }
    else
    {
        inst_bindless_stream_write_4(50u, 1u, uint(_19), 0u);
        _140 = vec4(0.0);
    }
2022-09-01 18:32:00 +00:00
Steven Perron
d51dc53d2c
Improve algorithm to reorder blocks in a function (#4911)
* Improve algorithm to reorder blocks in a function

In dead branch elimination, blocks can end up in a the wrong order, so
there is code to reorder the blocks in structured order.  The problem is
that the algorithm to do that is very poor.  It involves many searchs in
the function for the correct position to place the block, as well as
moving many block in the vector.

The solution is to write a specialized function in the function class
that will reorder the blocks in structured order.  After computing the
structured order, reordering the block can be done in linear time, with
very little overhead.
2022-08-31 11:06:15 -04:00
Spencer Fricke
fca39d5cb4
spirv-val: Better message for using OpTypeBool in input/output (#4901) 2022-08-29 12:47:16 -04:00
Spencer Fricke
f76431cbaf
spirv-val: Add SPV_KHR_ray_tracing storage class (#4868)
* Added VUID labels
2022-08-29 11:09:06 -04:00
jeremyg-lunarg
a98f05d02f
tests: Make InstrumentPass tests use SinglePassRunAndMatch<> and stateful pattern matching (#4897)
Using SinglePassRunAndMatch<> instead of SinglePassRunAndCheck<>
makes tests more concise and makes it possible to use pattern
matching features.

Using Effcee stateful pattern matching to make it less repetitive
to check for generated functions and global variables.

This approach isn't worth
it for DebugPrintf functions because the generated code will change
depending on how many parameters are passed to every debugPrintfEXT()
call.
2022-08-23 12:28:00 -06:00
Spencer Fricke
3c1a14b2b6
spirv-val: SBT Index for OpExecuteCallableKHR (#4900) 2022-08-18 13:42:25 -04:00
Spencer Fricke
0073a1fa36
spirv-val: Remove ImageWrite Texel todo (#4899) 2022-08-17 11:37:05 -04:00
Greg Fischer
71b2aee6c8
Add structs to eliminate dead input components (#4894)
Will eliminate all trailing members of input struct that are not
referenced.
2022-08-16 11:31:04 -04:00
Nathan Gauër
1728c1d40a
spirv-opt: fix copy-propagate-arrays index opti on structs. (#4891)
* spirv-opt: fix copy-propagate-arrays index opti on structs.

As per SPIR-V spec:
OpAccessChain indices must be OpConstant when indexing into a structure.

This optimization tried to remove load cascade. But in some scenario
failed:

```c
cbuffer MyStruct {
    uint my_field;
};

uint main(uint index) {
    const uint my_array[1] = { my_field };
    return my_array[index]
}
```

This is valid as the struct is indexed with a constant index, and then
the array is indexed using a dynamic index.
The optimization would consider the local array to be useless and
generated a load directly into the struct.

* spirv-opt: prevent creation of unused instructions

Copy-propagate-arrays optimization pass would create unused constants,
even if the optimization not completed.
This was caused by the way we handled OpAccessChain squashing: we
only referenced constants, and had to create them upfront.

Fixes #4887
Signed-off-by: Nathan Gauër <brioche@google.com>
2022-08-16 16:05:47 +02:00
Greg Fischer
9abacb34a5
Fix ADCE to not eliminate top level DebugInfo instructions (#4889)
Specifically, DebugSourceContinued, DebugCompilationUnit, and
DebugEntryPoint. These instructions are top-level instructions
which do not or may not have a user except for the tool and so
should not be eliminated.
2022-08-15 15:23:23 -06:00
Cassandra Beckley
3a8a961cff
Fix array copy propagation (#4890)
Array copy propagation was interpreting OpEntryPoint as a store
2022-08-11 09:59:37 -07:00
Steven Perron
0a43a84e02
Fix shuffle feeding shuffle with undef literal (#4883)
When folding a vector shuffle with an undef literal, it is possible that the
literal is adjusted so that it will then be interpreted as an index into
the input operands.  This is fixed by special casing that case, and not
adjusting those operands.

Fixes #4859
2022-08-10 09:04:35 -04:00
Steven Perron
ed3b9c83b1
Local access chain convert: check for negative indexes (#4884)
An access chain instruction interpretes its index operands as signed.
The composite insert and extract instruction interpret their index
operands as unsigned, so it is not possible to represent a negative
number.

This commit adds a check to the local-access-chain-convert pass to check
for a negative number in the access chain and to not do the conversion.

Fixes #4856
2022-08-09 17:33:04 +00:00
Spencer Fricke
f20e8d05f5
spirv-val: Add SPV_KHR_ray_tracing instructions (#4871) 2022-08-08 14:45:04 -04:00
Spencer Fricke
08c542d344
spirv-val: Label VUID 06997 (#4881) 2022-08-03 10:42:13 -04:00
alan-baker
b5d0bf285f
Require ColMajor or RowMajor for matrices (#4878)
Fixes #4875

* Require that matrices in laid out structs have RowMajor or ColMajor
  set as per SPIR-V section 2.16.2 (shader validation)
2022-07-29 15:08:48 -04:00
alan-baker
4773879b68
Update structure layout validation (#4876)
* Uniform block layout rules for matrices should use extended layouts by
  default
2022-07-29 10:16:54 -04:00
David Neto
8dc0030ecb
spirv-as: Avoid overflow when parsing exponents on hex floats (#4874)
* spirv-as: Avoid overflow when parsing exponents on hex floats

When an exponent is so large that it would overflow the int
type in the parser, saturate the exponent.
This allows extremely large exponents, and saturates
to infinity when the exponent is positive, and zero when the exponent
is negative.

Fixes #4721.

* Avoid unexpected narrowing conversions from arithmetic operations

Co-authored-by: Alastair F. Donaldson <alastair.donaldson@imperial.ac.uk>
2022-07-28 09:40:07 -04:00
Spencer Fricke
cc5fca057e
spirv-val: Fix Vulkan memory scope (#4869) 2022-07-26 15:14:21 -04:00
Alastair Donaldson
388ce0ee64
spirv-as: Avoid recursion when skipping whitespace (#4866)
Excessive whitespace can lead to stack overflow during parsing as each
character of skipped whitespace involves a recursive call. An
iterative solution avoids this.

Fixes #4729.
2022-07-26 10:56:04 -04:00
Spencer Fricke
e4cfa190df
spirv-val: Add SPV_KHR_ray_query (#4848) 2022-07-20 10:12:58 -04:00
Pankaj Mistry
60615b8ec6
Implement SPV_NV_bindless_texture related changes (#4847)
* Add validation for SPV_NV_bindless_texture
2022-07-19 14:41:19 -04:00
Spencer Fricke
93ebf698a0
spirv-val: Add OpConvertUToAccelerationStructureKHR (#4838) 2022-07-15 09:55:33 -04:00
Spencer Fricke
e2cf769302
spirv-val: Label VUID 06925 (#4852) 2022-07-13 10:05:52 -04:00
Greg Fischer
faa8d6a653
Revert "Optimize DefUseManager allocations (#4709)" (#4846)
This reverts commit d18d0d92e5.

This is reverted because it causes a 7X slowdown when legalizing
SPIR-V with NonSemantic.Shader.DebugInfo.100 instructions.
This is due to the creation of very large UseLists for several
heavily used operands for this extension combined with the fact
that the original commit changed the performance of Uselists to O(n).
2022-07-12 13:14:47 -06:00
Spencer Fricke
bc5c8760af
spirv-val: Add Vulkan decoration interface (#4831) 2022-07-07 13:03:52 -04:00
alan-baker
05de650371
Use structural reachability in CFG checks (#4849)
Fixes https://crbug.com/oss-fuzz48578

* Adds structural reachability to basic blocks
  * calculated in same manner as reachability, but using structural
    successors
* Change structured CFG validation to use structural reachability
  instead of reachability
* Fix some invalid reducer cases
2022-07-06 17:43:32 -04:00
David Neto
dcee3a5de0
Update validator diagnostics with "structurally dominated" (#4844)
The updated rules in SPIR-V 1.6 Rev2 use structural dominance,
so update the messages to match
2022-07-06 15:10:29 -04:00
Steven Perron
92fe420c8a
Reduce load size does not work for array with spec const size (#4845)
Arrays do not have to have a size that is known at compile time.  It
could be a spec constant.  In these cases, treat the array
as if it is arbitrarily long.  This commit will treat it like it is an
array of size UINT32_MAX.

Fixes https://crbug.com/oss-fuzz/47397.
2022-07-05 16:16:50 -04:00
Steven Perron
d5a3bfcf2f
Avoid undefined behaviour when getting debug opcode (#4842)
If the `instruction` operand in an extended instruction instruction is
too large, it causes undefined behaviour when that value is cast to the
enum for the corresponding set.  This is done with the
NonSemanticDebug100 instruction set.  We need to avoid the undefined
behaviour.

Fixes #4727
2022-07-05 14:14:29 -04:00
Steven Perron
32622ba7c6
DCE: clean up the cfg for all functions that were processed. (#4840)
Which functions are processed is determined by which ones are on the
call tree from the entry points before dead code is removed.  So it is
possible that a function is process because it is called from an entry
point, but the CFG is not cleaned up because the call to the function
was removed.

The fix is to process and cleanup every function in the module.  Since
all of the dead functions would have already been removed in an earlier
step of DCE, it should not make a different in compile time.

Fixes #4731
2022-07-05 12:23:32 -04:00
alan-baker
286e9c1187
Use structural dominance to validate cfg (#4832)
* Structural dominance introduced in SPIR-V 1.6 rev2
* Changes the structured cfg validation to use structural dominance
  * structural dominance is based on a cfg where merge and continue
    declarations are counted as graph edges
* Basic blocks now track structural predecessors and structural
  successors
* Add validation for entry into a loop
* Fixed an issue with inlining a single block loop
  * The continue target needs to be moved to the latch block
* Simplify the calculation of structured exits
  * no longer requires block depth
* Update many invalid tests
2022-06-29 23:32:20 -04:00
Mike
0b824324bc
Fix segfault in SpirvTools::Disassemble when printing (#4833)
When the `SPV_BINARY_TO_TEXT_OPTION_PRINT` option is specified, `spvtext` will not be created (see 37d2396cab/source/disassemble.cpp (L117)), and the attempt to dereference into its members (`spvtext->str` and `spvtext->length`) results in segmentation fault.

This is fixed by first checking if `spvtext` is nulll.

Co-authored-by: Steven Perron <stevenperron@google.com>
2022-06-29 12:05:00 -04:00
Steven Perron
66d88508dd
Build struct order only for the section needed when unrolling. (#4830)
We currently build the structured order for all nodes reachable from the
loop header when unrolling a loop.  However, unrolling only needs the
nodes in the loop and possibly the merge node.

To avoid needless computation, I have implemented a search that will
stop at the merge node.

Fixes #4827
2022-06-29 09:53:26 -04:00
Steven Perron
37d2396cab
Fix SplitLoopHeader to handle single block loop (#4829)
The code in `CFG::SplitLoopHeader` assumes the loop header is not the
latch.  This leads to it not being able to find the latch block.  This
has been fixed, and a test added.

Fixes #4527
2022-06-24 12:33:45 -04:00
Steven Perron
3c9fd7577f
Avoid if-conversion if both predecessors are the same (#4826)
If the predecessor blocks are the same, then there is only 1 value for the
OpPhi.  The simplition pass will simplify it, and it causes problems for
if-conversion.  In these cases, if-conversion can just punt.

Fixes #3554.
2022-06-24 15:28:06 +00:00
Steven Perron
76fe352190
Fail validation when RelaxedPrecision is applied to a type. (#4823)
* Fail validation when RelaxedPrecision is applied to a type.

Fixes #4723
Fixes #4725

* Fixup invalid test
2022-06-21 19:59:01 +00:00
David Neto
2eff41e707
Remove stray output to stdout from tests (#4816) 2022-06-20 10:57:44 -04:00
manas-kulkarni
fbcb6cf4c8
Ability to fold Constant Vector times Matrix and Matrix times vector instructions (#4818) 2022-06-16 13:54:12 -04:00
Spencer Fricke
bfc611b03e
spirv-val: Label 06807 and 06808 VUID (#4817) 2022-06-15 11:25:16 -04:00
Steven Perron
76ebfb989f
Avoid replacing access chain with OOB access (#4819)
An access chain could have a constant index that is an out of bounds
access.  This is valid spir-v, even if it can cause problems at runtime.
However, it is not valid to have an OpCompositeExtract with an out of
bounds access.  This means we have to stop local-access-chain-convert
from making that change.

Fixes #4605
2022-06-14 13:06:38 -04:00
David Neto
8f7f5024f8
Simplify invocation of snprintf (#4815) 2022-06-10 17:55:45 -04:00
Junda Liu
044ff1aabf
spirv-val: Add support for SPV_AMD_shader_early_and_late_fragment_tests (#4812)
- Update SPIR-V headers.
- Add validator support.
- Add validator tests.
2022-06-08 08:36:32 -04:00
Shahbaz Youssefi
c94501352d
spirv-val: Optimize struct field decoration lookup (#4809)
A std::set is used instead of std::vector, where the elements are
ordered by member index first.  Decorations for fields are now looked up
by going over the range of decorations for the member only, instead of
the whole set.

In an ANGLE test that generates a struct with 4096 members, validation
goes down from ~140ms to ~90ms.  On debug builds, the difference is more
pronounced, going down from ~2.5s to ~600ms.
2022-06-02 11:32:38 -04:00
Nicolas Capens
130a05d2e3
Fold multiply and subtraction into FMA with negation (#4808)
This change adds a folding rule which transforms x * y - a and a - x * y
into FMA(x, y, -a) and FMA(-x, y, a), respectively.

While the SPIR-V instruction count remains the same, target instruction
sets typically feature FMA instruction variants that can negate an
operand. Also this transformation may unlock further optimizations which
eliminate the negation.

(Google bug: b/226145988)
2022-05-31 12:03:56 -04:00
Spencer Fricke
82d91083cb
spirv-val: Add PerVertexKHR (#4807) 2022-05-26 13:11:05 -04:00
Steven Perron
088cb1a5c8
Add more folding for composite instructions (#4802)
* Add move folding for composite instructions

Fold chains of insert into construct

If a chain of OpCompositeInsert instruction write to every element of a
composite object, then we can replace it with an OpCompositeConstruct.

Fold a construct fed by extracts to a single extract

We already fold an OpCompositeConstruct when it is simlpy reconstructing
an object that was decomposed by a series of OpCompositeExtract
instructions.  However, we do not do that if that object is an element
of a larger object.

I have updated the rule, so that if the original object is a an element
of a larger object, then the OpCompositeConstruct is replaced with a
single OpCompositeExtract from the larger object.

Fixes #4371.
2022-05-26 10:29:02 -04:00
stu-s
c267127846
Add SPV_KHR_fragment_shader_barycentric support (#4805)
* Add SPV_KHR_fragment_shader_barycentric support
2022-05-25 09:20:39 -04:00
Steven Perron
f74b85853c
Handle 64-bit integers in local access chain convert (#4798)
* Handle 64-bit integers in local access chain convert

The local access chain convert pass does on run on module that have
64-bit integers, even if they have nothing to to with access chains.
This is very limiting because other passes rely on the access chains
being removed. So this commit will add this functionality to the pass.
2022-05-10 17:02:14 +00:00
Daniele Vettorel
f7a6e3b9d5
Handle chains of OpAccessChain in replacing variable index access for flattened resources. (#4797) 2022-05-10 11:41:43 -04:00
Jaebaek Seo
ad3514b732
spirv-opt: add pass for interface variable scalar replacement (#4779)
Replace shader's stage variables whose types are array or matrix
with scalars/vectors.
For example,
```
Before:
  %foo = OpVariable %_ptr_Output__arr_v2float_uint_4 Output
After:
  %foo = OpVariable %_ptr_Output_v2float Output
  %foo_0 = OpVariable %_ptr_Output_v2float Output
  %foo_1 = OpVariable %_ptr_Output_v2float Output
  %foo_2 = OpVariable %_ptr_Output_v2float Output
```
2022-05-09 14:04:52 -04:00
JiaoluAMD
c11ea09652
spirv-opt : Add FixFuncCallArgumentsPass (#4775)
spirv validation require OpFunctionCall with memory object, usually this
is non issue as all the functions are inlined.
This pass deal with some case for
DontInline function. accesschain input operand would be replaced new
created variable
2022-05-06 10:39:26 -04:00
Daniel Koch
9e377b0f97
spirv-val: Add CullMaskKHR support (#4792)
Co-authored-by: sfricke-samsung <s.fricke@samsung.com>
2022-05-06 07:32:56 -04:00
Kévin Petit
7014be600c
Add support for SPV_KHR_subgroup_rotate (#4786)
- Add assembler/disassembler support
- Add validator support

Signed-off-by: Kevin Petit <kevin.petit@arm.com>
Change-Id: Iffcedd5d5e636a0e128a5906ffe634dd85727de1
2022-05-05 08:58:05 -04:00
JiaoluAMD
2c7fb9707b
Handle dontinline function in spread-volatile-semantics (#4776)
Handle function calls in spread-volatile-semantics
2022-05-04 10:52:58 -04:00
Steven Perron
1295dca8e2
Reapply "Add folding rule to generate Fma instructions (#4783)" (#4789)
This reverts commit 671f6e633f.

PR #4783 was reverted because it caused OpenCL CTS failures for clvk.
The was in clspv, which was not adding the no contract decoration when
it was required.  This has been fixed in
https://github.com/google/clspv/pull/845.  We can now reapply #4783.
2022-05-03 10:20:23 -04:00
Karol Herbst
edaf51038b
linker: Recalculate interface variables (#4784)
* linker: Recalculate interface variables

By resolving extern symbols Entry Points might access variables they
hadn't declared before.

* test/linker: add test to verify linked spir-vs importing functions validate

Without the fix Validate will complain about:

"ERROR: 9: Interface variable id <5> is used by entry point 'bar' id <1>, but is not listed as an interface\n  %5 = OpVariable %_ptr_Input_v3uint Input\n"
2022-05-03 13:23:02 +00:00
sindney
46492aa45a
spirv-opt: skips if_conversion when dontflatten is set (#4770) 2022-04-28 19:26:02 +00:00
Daniele Vettorel
671f6e633f
Revert "Add folding rule to generate Fma instructions (#4783)" (#4785)
This reverts commit 2b2b0282af.
2022-04-20 10:55:20 -04:00
Steven Perron
2b2b0282af
Add folding rule to generate Fma instructions (#4783)
Adding Fma instruction can speed up the code.  This was requested by
swiftshader, so they do not have to do this analysis themselves.  It can
also help reduce the code size, and the work the ICD compilers have to
do.
2022-04-19 11:25:07 -04:00
Steven Perron
92c17edde7
Don't try to unroll loop with step count 0. (#4769)
These loop are infinite loop, so there is no reason to unroll the loop.
Fixes #4711.
2022-04-11 10:21:15 -04:00
Shahbaz Youssefi
5760114d77
spirv-diff: Fix OpTypeFunction matching w.r.t operand count (#4771)
The code accidentally expected OpTypeFunction operand count to match.
This is fixed so that OpTypeFunction instructions with different operand
counts are considered not matching.
2022-04-01 09:04:26 -04:00
Shahbaz Youssefi
bd325d2984
spirv-diff: Basic support for OpTypeForwardPointer (#4761)
Currently, the diff tool matches types bottom up, so on every
instruction it expects to know if its operands are already matched or
not.  With cyclical references, it cannot know that.  Type matching
would need significant rework to be able to support such a use case; for
example, it may need to maintain a set of plausable matches between type
pointers that are forward-referenced, and potentially back track when
later the types turn out to be incompatible.

In this change, OpTypeForwardPointer is supported in the more common and
trivial case.  Firstly, forwarded type pointers are only matched if they
have they have the same storage class and point to the same type opcode:

- In the presence of debug info, matching is done only if the names are
  unique in both src and dst.
- In the absence of debug info, matching is done only if there is only
  one possible matching.

Fixes: #4754
2022-03-28 17:01:07 +00:00
sfricke-samsung
0c670ef1d9
spirv-as: Add opcode name when possible (#4757) 2022-03-28 14:46:39 +00:00
Jaebaek Seo
05745cc9d4
Handle shaders without execution model in spread-volatile-semantics (#4766)
spread-volatile-semantics pass spreads Volatile semantics for builtin
variables used by certain execution models based on
VUID-StandaloneSpirv-VulkanMemoryModel-04678 and
VUID-StandaloneSpirv-VulkanMemoryModel-04679 (See "Standalone SPIR-V
Validation" section of Vulkan spec "Appendix A: Vulkan Environment for
SPIR-V"). Therefore, shaders without execution model (e.g., used only
for linkage) are not the target of the pass. This commit lets the pass
just return SuccessWithoutChange in that case.
2022-03-25 17:54:46 +00:00
sfricke-samsung
fa5d424830
spirv-val: Add more Vulkan VUID labels (#4764) 2022-03-25 09:29:19 -04:00
Nikita
a3fbc9331b
Support SPV_KHR_uniform_group_instructions (#4734) 2022-03-25 08:32:50 -04:00
sfricke-samsung
90728d2dff
spirv-val: Clean up VariablePointers logic (#4755) 2022-03-24 12:02:29 -04:00
sfricke-samsung
b3c1790632
spirv-val: Add Vulkan 32-bit bit op Base (#4758) 2022-03-23 13:55:42 -04:00
sfricke-samsung
9668d2e4e4
spirv-val: Label and add test for PSB Aligned (#4756) 2022-03-23 11:08:21 -04:00
Greg Fischer
9d1b572884
spirv-opt: (WIP) Eliminate Dead Input Component Pass (#4720)
This adds the --eliminate-dead-input-components pass which currently
removes trailing unused components from input arrays.

Fixes #4532
2022-03-22 20:50:52 -06:00
sfricke-samsung
f8cd51431e
spirv-val: Add better error code for invalid operand (#4753) 2022-03-22 15:37:38 -04:00
sfricke-samsung
7963fa13c7
spirv-val: Add Vulkan Dref not allowed 3D dim VUID (#4751) 2022-03-10 13:08:26 -05:00
sfricke-samsung
5c9d55a59a
spirv-val: Add Vulkan Image VUID 06214 (#4750) 2022-03-10 13:06:48 -05:00
sfricke-samsung
9700708570
spirv-val: Label Vulkan RuntimeArray VUID (#4749) 2022-03-10 13:05:26 -05:00
sfricke-samsung
ca59914c7a
spirv-val: Disallow array of push constants (#4742) 2022-03-10 12:57:20 -05:00
Steven Perron
0741f42738
Reset the id bound on the module in compact ids (#4744)
If the body of the module does not have any ids change, compact ids will
not change the id bound.  This can cause problems because the id bound
could be much higher than the largest id in that is used.  It should be
reset any time it is not the larger id used + 1.

Fixes #4604
2022-03-07 20:33:01 +00:00
Steven Perron
48a36c72e4
Better handling of 0xFFFFFFFF when folding vector shuffle (#4743)
When folding a vector shuffle feeding a vector shuffle, we do not
propagate an 0xFFFFFFFF, which has a special meaning, correctly.  We
adjust the value making it lose it meaning as an undefined value.

Fixes #4581
2022-03-07 19:35:57 +00:00
Steven Perron
4fa1a6f9b4
Generalize assert in ccp (#4735)
CCP does not want to fold an instruction unless it folds to a constant.
There is an asser to check for this.  The question if a spec constant
counts as a constant.  The constant folder considers a spec constant a
constand, but CCP does not.  I've fixed the assert in CCP to match what
the folder does.  It should not require any new changes to CCP.
2022-03-07 19:33:10 +00:00
Steven Perron
920156cf18
Add pass to remove DontInline function control (#4747)
Swift shader needs a way to inline all functions, even those marked as
DontInline.  See https://github.com/KhronosGroup/SPIRV-Tools/pull/4471.
This implements the suggestion I made in the PR.  We add a pass that
will remove the DontInline function control, so that the inlining passes
will inline them.

SwiftShader will still have to modify their code to add this pass before
the other passes are run.
2022-03-07 12:45:17 -05:00
sfricke-samsung
273d2a45ad
spirv-val: Label VUID 06491 (#4745) 2022-03-07 12:30:05 -05:00
Steven Perron
0b8426346d
Don't rebuilt valid analyses. (#4733)
The function `BuildInvalideAnalyses` will be rebuilt for every analysis that
has been requested, but it is not necessary.  It also can cause problems
because if the CFG needs to be rebuilt, so do the dominator trees.

This change will make the functionality match the description of the
function.
2022-03-04 20:16:42 +00:00
sfricke-samsung
d1addc44b2
spirv-val: Label Vulkan VUID 04734 (#4739) 2022-03-04 10:07:24 -05:00
Jeremy Hayes
598bc6744a
spirv-val: Validate DebugTypeMatrix (#4732) 2022-03-04 08:54:05 -05:00
pd-valve
d18d0d92e5
Optimize DefUseManager allocations (#4709)
* Optimize DefUseManager allocations

Saves around 30-35% of compilation time.

For inst->use_ids, use a pool linked list instead of allocating vectors for every instruction.  For inst->uses, use a "PooledLinkedList"' -- a linked list that has shared storage for all nodes.  Neither re-use nodes, instead we do a bulk compaction operation when too much memory is being wasted (tuneable).

Includes separate PooledLinkedList templated datastructure, a very special case construct, but split out to make the code a little easier to understand.
2022-02-15 19:17:30 -05:00
pd-valve
a123632ed9
Optimize Type::HashValue (#4707)
Incrementally compute the hash instead of collecting words

Avoids allocating temporary space in a std::vector and std::u32string, and making three passes over all the hashed data.
Switch to using std::vector to prevent processing duplicates instead of std::unordered_set: avoids an allocation/deletion every call to ComputeHashValue, and ends up faster due to much better cache behaviour and smaller constant-factor when searching the (generally very small) list.

In my test case, made Type::HashValue go from 7.5% of compilation time to .5%
2022-02-15 18:57:39 +00:00
sfricke-samsung
471428a04f
spirv-opt: Add OpExecutionModeId support (#4719)
Needed for Vulkan1.3 adding LocalSizeId support
2022-02-14 14:33:29 +00:00
Natalie Chouinard
72e4475b41
Handle propagation of arrays with decorations (#4717)
When copy propagating, OpDecorate instructions can be copied as is. For
array flattening, they should be ignored.
2022-02-11 16:13:14 -05:00
Shahbaz Youssefi
0ad83f9139
spirv-diff: Match OpSpecConstantComposite correctly (#4704)
OpSpecConstantComposite is not decorated with SpecId, and so is matched
similarly to OpConstantComposite.
2022-02-11 15:29:42 +00:00
pd-valve
44923beb52
Optimize Instruction::Instruction (#4705)
Avoid constructing temporary vector + copying operands multiple times.
Add SmallVector(InputIt first, InputIt last), matching std::vector.
2022-02-10 18:31:07 +00:00
Ryan Harrison
a383c476e6
Remove reference to protobuf internals from fuzzers (#4701)
In newer versions of protobuf the Status building code has been made
internal, so that embedders cannot build their own instances like is
being done here.

Changing this code to just use the .ok() method on the status object,
since if the status is OK or not is what is actually being tested.

This will make it easier in the future to update external/protobuf.
2022-02-10 10:41:24 -05:00
Greg Fischer
ff91f9449b
[spirv-val] Allow 0 Component Count for DebugTypeArray for Shader (#4706)
Rev 7 of NonSemantic.Shader.DebugInfo.100 was updated to allow zero
component count for for DebugTypeArray to represent runtime array.
2022-02-09 17:58:55 -07:00
David Neto
9fe41e60d8
Update test for parsing memory access masks (#4703)
* Update test for parsing memory access masks

Needed to support SPV_INTEL_memory_access_aliasing extension

There is a negative test that checks unused mask bits.
Some of those bits are now sued by the new Intel extension.

* Update deps for new SPIRV-Headers
2022-02-09 18:02:19 +00:00
Shahbaz Youssefi
332475dbc9
spirv-diff: Handle OpSpecConstant array sizes (#4700)
Previously, array sizes were presumed to be OpConstant, which is not
necessarily true.  This change ensures OpSpecConstant array sizes as
matched exactly, instead of taken as OpConstant and matched by value.
2022-02-09 09:06:46 -05:00
Shahbaz Youssefi
9beb54513c
Stabilize the output of spirv-diff (#4698)
* Reimplement LCS used by spirv-diff

Two improvements are made to the LCS algorithm:

- The LCS algorithm is reimplemented to use a std::stack instead of
  being recursive.  This prevents stack overflow in the LCSTest.Large
  test.
- The LCS algorithm uses an NxM table.  Previously, entries of this
  table were {size_t, bool, bool}, which is now packed in 32 bits.  The
  first entry can assume a maximum value of min(N, M), which
  realistically for SPIR-V diff will not be larger than 1 billion
  instructions.  This reduces memory usage of LCS by 75%.

This partially reverts 845f3efb8a and
enables LCS tests.

* Stabilize the output of spirv-diff

std::map is used instead of std::unordered_map to ensure the output of
spirv-diff is identical everywhere.

This partially reverts 845f3efb8a and
enables spirv-diff tests.
2022-02-07 09:37:04 -05:00
Diego Novillo
845f3efb8a
Disable spirv-diff tests. (#4695)
This disables spirv-diff tests temporarily, since they are currently
failing on Windows builds.
2022-02-03 16:21:45 -05:00
Steven Perron
5b371918b9
Have scalar replacement use undef instead of null (#4691)
Scalar replacement generates a null when there value for a member will
not be used.  The null is used to make sure things are
deterministic in case there is an error.

However, some type cannot be null, so we will change that to use undef.
To keep the code simpler we will always use the undef.

Fixes #3996
2022-02-03 15:51:15 +00:00
Shahbaz Youssefi
7fa9e746ef
Introduce spirv-diff (#4611)
spirv-diff is a new tool that produces diff-style output comparing two
SPIR-V modules.  The instructions between the src and dst modules are
matched as best as the tool can, and output is produced (in src
id-space) that shows which instructions are removed in src, added in dst
or modified between them.  The order of instructions are not retained.

Matching instructions between two SPIR-V modules is not trivial, and
thus a number of heuristics are applied in this tool.  In particular,
without debug information, it's hard to match functions as they can be
reordered.  As such, this tool is primarily useful to produce the diff
of two SPIR-V modules derived from the same source.

This tool can be useful in a number of scenarios:

- Compare the SPIR-V before and after modifying a shader
- Compare the SPIR-V produced from a shader before and after compiler
  codegen changes.
- Compare the SPIR-V produced from a shader before and after some
  transformation or optimization.
- Compare the SPIR-V produced from a shader with different compilers.
2022-02-02 10:33:18 -05:00
Steven Perron
b846f8f1dc
Complete handling of RayQueryKHR type (#4690)
The handling of the RayQueryKHR type is not complete in the type
manager.  The tests were not picking this up.  I've added a test to make
sure that the `GenerateAllTypes` function actually does generate all of
the types.  Once it is added there other tests should pick up on the
other parts that were missing.
2022-01-31 15:44:32 +00:00
alan-baker
20b122b2e0
Fix handling of Nontemporal image operand (#4692)
* Nontemporal image operand shouldn't expect a following operand
2022-01-28 21:12:03 -05:00
luzpaz
65ecfd1093
Fix various source comment (doxygen) typos (#4680)
Found via `codespell -q 3 -L fo,lod,parm
2022-01-26 15:13:08 -05:00
Jaebaek Seo
fb9a10cd48
spirv-opt: add pass to Spread Volatile semantics (#4667)
Add a pass to spread Volatile semantics to variables with SMIDNV,
WarpIDNV, SubgroupSize, SubgroupLocalInvocationId, SubgroupEqMask,
SubgroupGeMask, SubgroupGtMask, SubgroupLeMask, or SubgroupLtMask BuiltIn
decorations or OpLoad for them when the shader model is the ray
generation, closest hit, miss, intersection, or callable shaders. This
pass can be used for VUID-StandaloneSpirv-VulkanMemoryModel-04678 and
VUID-StandaloneSpirv-VulkanMemoryModel-04679 (See "Standalone SPIR-V
Validation" section of Vulkan spec "Appendix A: Vulkan Environment for
SPIR-V").

Handle variables used by multiple entry points:

1. Update error check to make it working regardless of the order of
   entry points.
2. For a variable, if it is used by two entry points E1 and E2 and
   it needs the Volatile semantics for E1 while it does not for E2
  - If VulkanMemoryModel capability is enabled, which means we have to
    set memory operation of load instructions for the variable, we
    update load instructions in E1, but do not update the ones in E2.
  - If VulkanMemoryModel capability is disabled, which means we have
    to add Volatile decoration for the variable, we report an error
    because E1 needs to add Volatile decoration for the variable while
    E2 does not.

For the simplicity of the implementation, we assume that all functions
other than entry point functions are inlined.
2022-01-25 13:14:36 -05:00
alan-baker
6938af7f82
Vulkan 1.3 (#4686)
* Add new environment enum for Vulkan 1,3
* Do not require --allow-localsizeid in Vulkan 1.3 to use LocalSizeId
  execution mode
2022-01-25 10:36:08 -05:00
Pierre Moreau
58d8b4e29c
linker: Address conversion error introduced in earlier rework (#4685)
* linker: Address conversion error introduced in earlier rework

Also rework the code slightly to first compute the new ID bound and
validate it, and only then, offset all existing IDs.

This makes those two steps clearer, and avoids potentially overflowing
the IDs within a module (even if that would have been caught later on).

Fixes: c3849565 ("Linker improvements (#4679)")
Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/4684

* test/linker: Disable IdsLimit tests for now

They are taking too long to run and results in the CI jobs timing out.
2022-01-24 13:40:57 -05:00
Pierre Moreau
c38495656d
Linker improvements (#4679)
* test/linker: Code factorisation and small tweaks

* linker: Do not fail when going over limits

The limits are minima and implementations or APIs might support higher
limits, so just warn the user about it. And only check for the limits
right before emitting the binary, as limits might change earlier when
removing duplicate instructions, function prototypes, etc.
The only check performed right before merging, is making sure the ID
bound will not overflow the 32 bits following the merge.

Also, use the defines for the limits instead of hard-coding them.

* linker: Require a memory model in each input module

The existing code could run into weird situation. For example, if the
first module had no memory model, it would not emit any memory model
(sort of reasonable) and would accept without complains all possible mix
from later modules as it would not verify them.

* linker: Replace hex version with SPV_SPIRV_VERSION_WORD

* linker: Error out when linking together different versions

Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/4135

* tools/linker: Do not write to disk if linking failed

Also, do not consider warnings as errors.

* tools/linker: Fix formatting in help message

* tools/linker: Further clarify the use of --target-env

Also update the text for the default version to reflect the change made
in 7d768812 ("Basic support for SPIR-V 1.6 (#4663)").
2022-01-22 15:40:19 -05:00
Alastair Donaldson
c5ee1bc7bd
Fix opt fuzzer test harness (#4670)
The test harness for the opt fuzzer was failing to consider that the
input might use a very large id bound, despite no id approaching this
bound actually being used.

This change modifies the test harness to use the module's id bound,
rather than looking through the module for large ids.

Fixes: oss-fuzz:42386
2022-01-07 15:03:29 +00:00
David Neto
df2aad68b9
val: interface struct with builtins must be Block (#4665)
For a shader input/output interface variable of structure type:
If the structure has BuiltIn members, then the structure type
must be Block decorated.

Otherwise, the variable, or the struct members must have locations,
but nothing can have both a location be a BuiltIn.

Implements validation needed to reject the example in
https://github.com/KhronosGroup/SPIRV-Registry/issues/134
2021-12-16 16:48:12 -05:00
David Neto
5d0e3240f0
Patch location validation VUIDs (#4664)
* spirv-val: Add Vulkan Location VUID

* Simplify: interface checking already does all the work

Co-authored-by: sfricke_samsung <s.fricke@samsung.com>
2021-12-16 15:25:23 -05:00
alan-baker
7d768812e2
Basic support for SPIR-V 1.6 (#4663)
* Basic support for SPIR-V 1.6

* Update SPIRV-Headers deps
* Add new environment enum for SPIR-V 1.6
* Make default environment 1.6 for most tools
* Update tests
* Disallow conditional branch with duplicate labels
* Disallow Dim=Buffer with sampled images
* Do not require the non-semantic extension after SPIR-V 1.5
2021-12-15 14:38:28 -05:00
Steven Perron
b7251d4fb7
reflect debug (#4662)
The pass to remove the nonsemantic information and instructions
is used for drivers or tools that may not support them.  Debug
information was only partially handle, which is causing a
problem.  We need to either fully remove debug information or
not remove it all.  Since I can see it being useful to keep the
debug information even when the nonsemantic instructions are
removed, I propose we do not remove debug info.

Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/4269
2021-12-15 11:06:51 -05:00
Steven Perron
354a46a2a2
Rename strip reflect to strip nonsemantic (#4661)
In https://github.com/KhronosGroup/SPIRV-Tools/pull/3110, the strip reflect
pass was changed to also remove all explicitly nonsemantic instructions.  This
makes it so that the name of the pass no longer reflects what the pass actually
does.  This change renames the pass so that it reflects what the pass actaully does.
2021-12-15 09:55:30 -05:00
Alastair Donaldson
f0351b7bc6
Avoid id bound errors during opt fuzzing (#4658)
Use a very large id bound when fuzzing the optimizer, and check that the
input does not ids that are too close to this bound. This should make it
impossible in practice for an id overflow to occur.

Fixes #4657.
2021-12-13 10:56:52 +00:00
Alastair Donaldson
e452792594
Simplify the as fuzzer target (#4647)
Makes the logic in the as fuzzer target closer to the logic of the
spirv-as tool.

Fixes #4643
2021-12-10 10:06:23 -05:00
Sebastien Alaiwan
a2260d3b1f
Fix compilation (#4656)
* Delete public accessor, whose only user is one unit-test

The underlying container type becomes invisible from the outside.

* Fix compilation
2021-12-09 12:42:53 -05:00
Marius Hillenbrand
1ed847f438
Fix endianness of string literals (#4622)
* Fix endianness of string literals

To get correct and consistent encoding and decoding of string literals
on big-endian platforms, use spvtools::utils::MakeString and MakeVector
(or wrapper functions) consistently for handling string literals.

- add variant of MakeVector that encodes a string literal into an
  existing vector of words
- add variants of MakeString
- add a wrapper spvDecodeLiteralStringOperand in source/
- fix wrapper Operand::AsString to use MakeString (source/opt)
- remove Operand::AsCString as broken and unused
- add a variant of GetOperandAs for string literals (source/val)
... and apply those wrappers throughout the code.

Fixes  #149

* Extend round trip test for StringLiterals to flip word order

In the encoding/decoding roundtrip tests for string literals, include
a case that flips byte order in words after encoding and then checks for
successful decoding. That is, on a little-endian host flip to big-endian
byte order and then decode, and vice versa.

* BinaryParseTest.InstructionWithStringOperand: also flip byte order

Test binary parsing of string operands both with the host's and with the
reversed byte order.
2021-12-08 12:01:26 -05:00
Diego Novillo
c75a1a46f3
Fix https://github.com/KhronosGroup/SPIRV-Tools/issues/4462 (#4651)
This prevents CCP from making constant -> constant transitions when
evaluating instruction values.  In this case, FClamp is evaluated twice.
On the first evaluation, if computes FClamp(0.5, 0.5, -1) which returns
-1.  On the second evaluation, it computes FClamp(0.5, 0.5, VARYING)
which returns 0.5.

Both fold() computations are correct given the semantics of FClamp() but
this causes a lateral transition in the constant lattice which was not
being considered VARYING by CCP.
2021-12-02 10:40:28 -05:00
Natalie Chouinard
d0a827a9f3
Copy OpDecorateStrings in DescriptorScalarReplacementPass (#4649)
Along with OpDecorate, also clone the OpDecorateString instructions for
variables created in the descriptor scalar replacement pass.

Fixes microsoft/DirectXShaderCompiler#3705
2021-11-29 02:11:22 -05:00
Steven Perron
8c155b364c
Manually fold floating point division by zero (#4637)
See https://github.com/KhronosGroup/SPIRV-Tools/issues/4636 for details.

Fixes #4636.
2021-11-24 14:13:58 -05:00
alan-baker
4b092d2ab8
Allow ADCE to remove dead inputs (#4629)
* https://github.com/KhronosGroup/Vulkan-Docs/issues/666 clearly
  specified that interfaces do not require an input if there is an
  associated output
* ADCE can now remove unused input variables (though they are kept if
  the preserve interfaces option is used)
2021-11-16 15:54:17 -05:00