Commit Graph

987 Commits

Author SHA1 Message Date
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
Nathan Gauër
b49a2caa7c
Revert "test" (#4974)
This reverts commit da215f10c9.
2022-10-27 14:17:31 +02:00
Nathan Gauër
da215f10c9 test 2022-10-26 16:42:29 +00: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
Spencer Fricke
49230a2307
spirv-opt: Remove unused folding rule (#4942) 2022-09-23 14:02:01 -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
Steven Perron
f98473ceeb
Remove spvOpcodeTerminatesExecution (#4931)
* Remove `spvOpcodeTerminatesExecution`

This function is the same as `spvOpcodeIsAbort` except for
OpUnreachable.  The names are so close in meaning that it is hard to
distinguish them.  I've removed `spvOpcodeTerminatesExecution` since it
is used in only a single place.  I've special cased OpUnreachable in
that location.

At the same time, I fixed up some comments related to the use of the
TerminatesExecution and IsAbort functions.

Following up on #4930.

* Fix comments
2022-09-21 16:10:58 -04:00
Greg Fischer
11d0d16227
Cleanup code for 272e4b3d0 (#4934)
Removed now unused DebugDeclare visibility logic for generating
DebugValue.

Also eliminated the phi sort introduced in 272e4b3. This should have
been removed in the first commit.
2022-09-20 15:27:23 -06: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
Steven Perron
529955e03d
Improve time to build dominators (#4916)
Changed a couple small parts of the algorithm to reduce time to build
the dominator trees.  There should be no visible changes.

Add a depth first search algorithm that does not run a function on
backedges.  The check if an edge is a back edge is time consuming, and
pointless if the function run on it is a nop.
2022-09-02 16:27:10 +00:00
Spencer Fricke
4386afb057
spirv-opt: Remove unused fold spec const code (#4906) 2022-09-02 16:24:02 +00: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
Greg Fischer
b5d1040b94
Fix ADCE to mark scope and inlined_at of line instructions as live. (#4910) 2022-08-31 18:10:17 -04: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
Greg Fischer
b41e3e1311
Disable DebugInfoMgr during the entire CompactIds pass (#4905)
This is because the DebugInfo manager requires valid SPIR-V
which is not always true during this pass.

Add comment
2022-08-23 12:01:32 -06: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
Nathan Gauër
0ebcdc4d19
Allow spirv-opt print-all to show pretty IDs (#4888)
Disassembler was called with non-default params, loosing FRIENDLY_NAMES.
This commit changes the call options to allow the spirv-opt to show
friendly names instead of raw-ids. Might be more helpful when reading
the SPIRV-opt output.

Fixes #4882

Signed-off-by: Nathan Gauër <brioche@google.com>
2022-08-09 14:10:36 -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
Pankaj Mistry
54cd5e1963
spirv-opt : SPV_NV_bindless_texture related changes (#4870) 2022-07-29 19:28:27 +00:00
Jamie Madill
a90ccc2405
Remove default copy constructor in header. (#4879)
A recent libc++ roll in Chrome warned of a deprecated copy. We're
still looking if this is a bug in libc++ or a valid warning, but
removing the redundant line is a safe workaround or fix in either
case.

See discussion in https://crrev.com/c/3791771
2022-07-29 18:26:37 +00: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
Greg Fischer
69e1deabc1
Fix small bug traversing users in interface_var_sroa (#4850)
Fix code that is traversing def-use user structure at the same time
that it is changing it. This is dicey at best and error prone at worst.
This was uncovered making a change to the id_to_user representation.
2022-07-08 13:11:22 -04:00
Steven Perron
5f4284aa78
Add limit for scalar replacment when fuzzing (#4843)
The fuzzer cretes code with very large array, and scalar replacement
times out.  Adding a limit on the size of the composites that will be
split when fuzzing.

Fixes https://crbug.com/oss-fuzz/48630
2022-07-05 20:12:58 -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
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
Alastair Donaldson
f2dfa53ae5
Avoid unrolling large loops while fuzzing (#4835)
Uses a preprocessor macro to bail out of unrolling loops with large
iteration counts during fuzzing, to reduce the number of
timeouts/memouts that arise.

Related issue: #4728.
2022-06-29 09:12:09 -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
PENGUINLIONG
c4ed5157dc
Fixed crash unrolling loops with residual iterations (#4820) 2022-06-23 16:01:44 -04:00
Steven Perron
845d98d468
Do not check if the binary changed if encoding is different (#4824)
There is an assert that verifies that the binary did not change when the
optimizer said that it did not.  However, if the input binary is in big endian
format, the optimizer will encode the optimized binary in little endian.  This
causes the assert to fail.  Since we do not believe that anybody cares about a
big endien formate, we will disable the assert in that case.

Fixes #4722
2022-06-21 19:58:21 +00:00
Steven Perron
4f321f862a
Avoid undefined divide-by-0 (#4821)
The Reciprocal function expects a divide-by-0 to return nan,and then Reciprocal will return 0.

Since the divide-by-0 is actually undefined, we will identify this case early, and return 0.

No new tests are needed because we already tests folding divide-by-0.

Fixes #4715
2022-06-21 11:37:34 -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
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
strangewiz
fad68a7551
Fix usage of sprintf. (#4811) 2022-06-08 19:49:46 +00: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
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