Commit Graph

1159 Commits

Author SHA1 Message Date
Jaebaek Seo
0cd3e599ae Validator: correct out of bound check for OpMemberDecorate (#1881)
The number that indicates a member in OpMemberDecorate must be less
than the number of total members of struct.
2018-09-18 10:16:46 -04:00
Steven Perron
7075c49923
Add dummy loop in merge-return. (#1896)
The current implementation of merge return can create bad, but correct,
code.  When it is not in a loop construct, it will insert a lot of
extra branch around code.  The potentially large number of branches are
bad.  At the same time, it can separate code store to variables from
its uses hiding the fact that the store dominates the load.

This hurts the later analysis because the compiler thinks that multiple
values can reach a load, when there is really only 1.  This poorer
analysis leads to missed optimizations.

The solution is to create a dummy loop around the entire body of the
function, then we can break from that loop with a single branch.  Also
only new merge nodes would be those at the end of loops meaning that
most analysies will not be hurt.

Remove dead code for cases that are no longer possible.

It seems like some drivers expect there the be an OpSelectionMerge
before conditional branches, even if they are not strictly needed.
So we add them.
2018-09-18 08:52:47 -04:00
Steven Perron
5f599e700e
Fix infinite loop in dead-branch-elimination (#1891)
* Create structed cfg analysis.

There are lots of optimization that have to traverse the CFG in a
structured order just because it wants to know which constructs a
basic block in contained in.  This adds extra complexity to these
optimizations, for causes too much refactoring of older optimizations.

To help with this problem, I have written an analysis that can give this
information.

* Identify branches breaking from loops.

Dead branch elimination does a search for a conditional branch to the
end of the current selection construct.  This search assumes that the
only way to leave the construct is through the merge node.  But that is
not true.  The code can jump to the merge node of a loop that contains
the construct.

The search needs to take this into consideration.
2018-09-17 13:00:24 -04:00
Lei Zhang
63265097e5
Add support for VK_KHR_shader_atomic_int64 in validator 2018-09-14 14:07:25 -04:00
Steven Perron
6d5f1bc2e8
Allow merge blocks to merge two header blocks in some cases. (#1890)
In merge blocks, we do not allow the merging of two blocks with merge
instructions.  This is because if the two block are merged only 1 of
those instructions can exists.  However, if the successor block is the
merge block of the predecessor, then we can delete the merge instruction
in the predecessor.  In this case, we are able to merge the blocks.
2018-09-14 13:37:18 -04:00
Jaebaek Seo
2c2fee7979 Validator: check OpTypeBool inside Blocks (#1405)
OpTypeBool can only be used with non-externally visible shader
Storage Classes: Workgroup, CrossWorkgroup, Private, and Function.
2018-09-10 13:33:13 -04:00
Steven Perron
75c1bf2843
Add option for the max id bound. (#1870)
* Create a new entry point for the optimizer

Creates a new struct to hold the options for the optimizer, and creates
an entry point that take the optimizer options as a parameter.

The old entry point that takes validator options are now deprecated.
The validator options will be one of the optimizer options.

Part of the optimizer options will also be the upper bound on the id bound.

* Add a command line option to set the max value for the id bound.  The default is 0x3FFFFF.

* Modify `TakeNextIdBound` to return 0 when the limit is reached.
2018-09-10 11:49:41 -04:00
Steven Perron
f62d7978fc
Add validation check for arrays of void type. (#1880)
In the definition of an array
(https://www.khronos.org/registry/spir-v/specs/1.2/SPIRV.html#Array),
it specfically mentions that array elements have non-void type.  I've
added a check for that in this PR.

http://crbug.com/879016
2018-09-10 09:21:32 -04:00
David Neto
7600fc0e19 Update Dim capabilities
Corresponds to grammar changes for SPIR-V 1.3 Rev4.
2018-09-06 13:41:31 -04:00
David Neto
571251c8f8 Support SPV_KHR_vulkan_memory_model rev2
Support collapsed into one commit:
- Asm/Dis support for SPV_KHR_vulkan_memory_model
- Add Vulkan mem model image operands to switch
- Add TODO for source/validate_image.cpp
- val: Image operands NonPrivateTexelKHR, VolatileTexelKHR have no operands
  This is required for memory model tests to pass SPIR-V validation.
- Round trip tests: Test new flags on OpCopyMemory*
2018-09-06 13:30:32 -04:00
Corentin Wallez
21bcb9d8b9 BUILD.gn: Make a better interface with dependents. (#1877)
This splits the spvtools_config into a public and private part to avoid
leaking internal bits to dependents. A new target is added for the
public headers so that "gn check" works for dependents.

Also formats test/fuzzers/BUILD.gn
2018-09-06 10:50:27 -04:00
Tobin Ehlis
58e53ea82f Fix sign mismatch warning
Cast negative ints to uint32_t to avoid int/uint comparison warning.
2018-08-31 17:51:43 -04:00
Alan Baker
cb0f1f565b Remove struct member offset monotonicity check
Fixes #1822

* Remove check that struct member offsets must be monotonic
 * All environments match Vulkan behaviour now
 * updated offending tests
2018-08-31 09:45:45 -04:00
Steven Perron
482b1744ca
Validate all type ids. (#1868)
* Validate all type ids.

The validator does not check if the type of an instruction is actually
a type unless the OpCode has a specific requirement.  For example,
OpFAdd is checked, but OpUndef is not.

The commit add a generic check that if there is a type id then the id
defines a type.

http://crbug.com/876694

* Merge other checks for type into new one.

There are a couple check that the type id is a type for specific
opcodes.  Those have been mereged into 1.

Small changes to other test cases to make them valid enough for the
purpose of the test.
2018-08-27 23:45:32 -04:00
Steven Perron
06b42949b6
Validate uses of OpTypeFunction. (#1867)
In the specification of `OpTypeFunction`, it says

> OpFunction is the only valid use of OpTypeFunction.

This commit add a check in the validator for this rule.

A test started to fail because the new check happens before the check
the test case is testing.  Updated the test case to still fail the
check it was suppose to fail originally.

http://crbug.com/874571
2018-08-27 11:41:25 -04:00
Steven Perron
d746681fe9
Copy decorations when creating new ids. (#1843)
* Copy decorations when creating new ids.

When creating a new value based on an old value, we need to copy the
decorations to the new id.  This change does this in 3 places:

1) The variable holding the return value of the function generated by
merge return should get decorations from the function.

2) The results of the OpPhi instructions should get decorations from the
variable they are replacing in the ssa writer.

3) In local access chain convert the intermediate struct (result of
OpCompositeInsert) generated for the store replacement should get its
decorations from the variable being stored to.

Fixes #1787.
2018-08-24 11:55:39 -04:00
Steven Perron
b4d3618f77
Don't "break" from selection constructs. (#1862)
If seems like at least 1 driver does not like a condition jump to the end
of a selection construct.  We are generating these in the merge return
pass.  This change stops merge return from generating this sequence.

Part of #1861.
2018-08-23 14:38:25 -04:00
Steven Perron
6c73b1fb70
Update the order when predicating blocks. (#1859)
When doing predicate blocks, we need to traverse every block in
structured order in order to keep track of which construct a block is
contained in.  The standard way of traversing code in structured order
is to create a list with all of the nodes in order.  However, when
predicating blocks, new blocks are created, and those blocks are missed.
This causes branches that go too far.

The solution is to update the order as new blocks are created.  Since
we are using an std::list, we do not have to worry about invalidation of
iterators when changing the list.
2018-08-23 12:59:31 -04:00
Alan Baker
c5b38062ec Moving constant opcode validation into a new file
* Split constant opcode validation out of idUsage and into
validate_constants.cpp
 * minor style fixes
 * reduced duplication
 * fixed an issue with array sizing
2018-08-21 17:30:26 -04:00
Steven Perron
19264ef42c
Have PredicateBlocks jump the existing merge blocks. (#1849)
* Refactor PredicateBlocks

Refactor PredicateBlocks so that we know which constructs a return
is contained in.  Will be used later.

* Have PredicateBlocks jump the existing merge blocks.

In PredicateBlocks, we currently skip instructions with side effects,
but it still follows the same control flow (sort-of).  This causes a
problem, when we are trying to predicate code in a loop.  We skip all
of the code with side effects (IV increment), but still follow the
same control flow (jump back the start of the loop).  This creates an
infinite loop because the code will keep jumping back to the start of
the loop without changing the values that effect the exit condition.

This is a large change to merge-return.  When predicating a block that
is in a loop or merge construct, it will jump to the merge block of the
construct.  Once out of all constructs we will generate code as we did
before.
2018-08-21 12:04:08 -04:00
Alan Baker
197b4597a0 Fix EvalInt32IfConst to fail on type instructions.
Fixes https://crbug.com/875842

* EvalInt32IfConst dereferenced a null pointer if a type instruction was
sent as the id
2018-08-21 11:59:00 -04:00
Steven Perron
d693a83e36
Handle breaks from structured-ifs in DCE. (#1848)
* Handle breaks from structured-ifs in DCE.

dead code elimination assumes that are conditional branches except for
breaks and continues in loops will have an OpSelectionMerge before them.
That is not true when breaking out of a selection construct.

The fix is to look for breaks in selection constructs in the same place
we look for breaks and continues for loops.
2018-08-21 11:54:44 -04:00
Steven Perron
45c235d41f
Have dead-branch-elim handle conditional exits from selections. (#1850)
When dead-branch-elim folds a conditional branch, it also deletes the
OpSelectionMerge instruction.  If that construct contains a
conditional branch to the merge node, it will not have its own
OpSelectionMerge.  When the headers merge instruction is deleted, the
the inner conditional branch will no longer be legal.  It will be a
selection to a node that is not a merge node.

We fix this up by moving the OpSelectionMerge to a new location if it is
still needed.
2018-08-21 11:49:56 -04:00
Diego Novillo
03000a3a38 Add testing framework for tools.
This forks the testing harness from https://github.com/google/shaderc
to allow testing CLI tools.

New features needed for SPIRV-Tools include:

1- A new PlaceHolder subclass for spirv shaders.  This place holder
   calls spirv-as to convert assembly input into SPIRV bytecode. This is
   required for most tools in SPIRV-Tools.

2- A minimal testing file for testing basic functionality of spirv-opt.

Add tests for all flags in spirv-opt.

1. Adds tests to check that known flags match the names that each pass
   advertises.
2. Adds tests to check that -O, -Os and --legalize-hlsl schedule the
   expected passes.
3. Adds more functionality to Expect classes to support regular
   expression matching on stderr.
4. Add checks for integer arguments to optimization flags.
5. Fixes #1817 by modifying the parsing of integer arguments in
   flags that take them.
6. Fixes -Oconfig file parsing (#1778). It reads every line of the file
   into a string and then parses that string by tokenizing every group of
   characters between whitespaces (using the standard cin reading
   operator).  This mimics shell command-line parsing, but it does not
   support quoting (and I'm not planning to).
2018-08-17 15:03:14 -04:00
Steven Perron
36d675a404
Change when instruction is registered in validator. (#1840)
When doing the validator checks, an instruction is currently registered
at the end of IdPass.  This creates an inconsistency.  In IdPass, an
instruction that uses its own result will treat that use as a forward
reference.  Then in the following passes it will not because the
definition can be found.

It seems best to update the state after all of the check have been done
for the current instruction.  This makes it consistent for all of the
passes.

This makes a different when trying to verify OpTypeStruct.

Fixes https://crbug.com/874372.
2018-08-15 13:18:47 -04:00
Steven Perron
e065cc208f
Keep decorations when replacing loads in access-chain-convert. (#1829)
In local-access-chain-convert, we replace loads by load the entire
variable, then doing the extract.  The extract will have the same value
as the load.  However, if the load has a decoration on it, the
decoration is lost because we do not copy any them to the new id.

This is fixed by rewritting the load into the extract and keeping the
same result id.

This change has the effect that we do not call DCEInst on the loads
because the load is not being deleted, but replaced.  This could leave
OpAccessChain instructions around that are not used.  This is not a
problem for -O and -Os.  They run local_single_*_elim passes and then
dead code elimination.  The dce will remove the unused access chains,
and the load elimination passes work even if there are unused access
chains.  I have added test to them to ensure they will not loss
opportunities.

Fixes #1787.
2018-08-15 09:14:21 -04:00
dan sinclair
ef678672fb
Remove source/message.h (#1838)
The code in source/message was only used in a single set of tests to
format the output results. This CL changes the test to verify the
message instead of all the error values and removes the source/message
code.
2018-08-14 15:41:21 -04:00
dan sinclair
1963a2dbda
Use MakeUnique. (#1837)
This CL replaces instances of reset(new ..) with MakeUnique.
2018-08-14 15:01:50 -04:00
dan sinclair
1553025f4c
Move make_unique to source/util. (#1836)
This MakeUnique code is used in places other then source/opt so move it
to source/utils.
2018-08-14 12:44:54 -04:00
Alan Baker
8cb949ad34 Validate correct opcode uses of OpFunction
Fixes https://crbug.com/873457

* Filed Khronos SPIR-V issue 352
* Updated bad tests
* Added new test
2018-08-14 10:13:06 -04:00
dan sinclair
5fc011b453
Move bit_stream, move_to_front and huffman_codec. (#1833)
bit_stream, move_to_front and huffman_codec are only used by
source/tools. Move into that directory to make the usage clearer.
2018-08-14 09:52:05 -04:00
alan-baker
ce4547bdc7
Disallow void types in structs (#1832)
Fixes #1831

* Adds validation check that void is not a member of a struct
 * added a test
2018-08-14 08:55:49 -04:00
Alan Baker
e7fdcdba75 Split function opcode validation into new files.
* Moved function opcode validation out of idUsage and into new files
 * minor style changes
 * General opcode checking is in validate_function.cpp
 * Execution limitation checking is in
 validate_execution_limitations.cpp
* Execution limitations was split into a new pass as it requires other
validation to register those limitations first.
2018-08-13 17:04:57 -04:00
dan sinclair
967bfa2d17
Remove unused stats maps and parameters (#1828) 2018-08-13 16:45:39 -04:00
Alan Baker
397e02442e Fixing heap overflow in validation.
* Changed entry point validation to check storage class of variable
instead of pointer
 * added a test
* Moved several checks after opcode validation
 * These checks should be able to guarantee individual instructions are
 ok
* Updated tests due to reordered checks
2018-08-13 15:23:30 -04:00
dan sinclair
da0f1dcccc
Move spirv_stats into tools/stats. (#1826)
The spirv_stats code is only used by the tools/stats module. This CL
moves the code to that module.
2018-08-13 11:48:25 -04:00
Alan Baker
7d4b0464a3 Split annotation opcode validation into new file.
* Moves annotation opcode checks from idUsage into a new pass
 * minor style updates
2018-08-08 15:43:11 -04:00
Alan Baker
f2a990022a Move type instruction validation into separate file
* Moved type instruction validation out of validation idUsage into a new
file
* Consolidate type unique pass into new file
* Removed one bad test
* Reworked validation ordering
2018-08-08 12:55:39 -04:00
Steven Perron
5c8b4f5a1c
Validate the input to Optimizer::Run (#1799)
* Run the validator in the optimization fuzzers.

The optimizers assumes that the input to the optimizer is valid.  Since
the fuzzers do not check that the input is valid before passing the
spir-v to the optimizer, we are getting a few errors.

The solution is to run the validator in the optimizer to validate the
input.

For the legalization passes, we need to add an extra option to the
validator to accept certain types of variable pointers, even if the
capability is not given.  At the same time, we changed the option
"--legalize-hlsl" to relax the validator in the same way instead of
turning it off.
2018-08-08 11:16:19 -04:00
Alan Baker
3a20879f4d Unify validation of OpCopyMemory*
Fixes #1800

* Refactored duplication of code between OpCopyMemory and
OpCopyMemorySized validation
* Fixed some bugs in OpCopyMemorySized validation
* Replaced asserts with checks
* Added new tests
2018-08-07 19:01:58 -04:00
Alan Baker
2896b8f0e5 Refactor where opcodes are validated
* Replaced uses in opcode validation of current_function()
* Added non-const accessor to function lookup in ValidationState_t
* Updated a couple bad tests due to check reordering
2018-08-07 10:29:30 -04:00
dan sinclair
508df9a387
Remove unused bit stream methods. (#1807)
This CL deletes methods from bit stream which are never used and moves
several to the anonymous namespace in the bit_stream test file.
2018-08-07 09:10:54 -04:00
dan sinclair
e3ea909ebe
Simplify MoveToFront (#1806)
This CL removes the templating from the MoveToFront code as all non-test
code uses uint32_t as the variable.
2018-08-07 09:10:25 -04:00
dan sinclair
05057c9846
Fixup readabilty/inheritance warnings (#1805)
This CL removes the un-needed virtual qualifiers from methods already
marked as override.
2018-08-07 09:10:03 -04:00
dan sinclair
eda2cfbe12
Cleanup includes. (#1795)
This Cl cleans up the include paths to be relative to the top level
directory. Various include-what-you-use fixes have been added.
2018-08-03 15:06:09 -04:00
Corentin Wallez
2d9a325264 Refactor BUILD.gn so can easily be embedded in other projects
1.
BUILD.gn: Don't use the extra Chromium clang warnings

Also removes the unused .gn secondary_sources.

2.

Move fuzzers in test/ instead of testing/

This frees up testing/ to be the git subtree of Chromium's src/testing/
that contains test.gni, gtest, gmock and libfuzzer

3.

DEPS: get the whole testing/ subtree of Chromium

4.

BUILD.gn: Simplify the standalone gtest targets

These targets definitions are inspired from ANGLE's and add a variable
that is the path of the googletest directory so that it can be made
overridable in future commits.

6.

BUILD.gn: Add overridable variables for deps dirs

This avoids hardcoded paths to dependencies that make it hard to
integrate SPIRV-Tools in other GN projects.
2018-08-03 10:06:11 -04:00
dan sinclair
7861df9bb3
Remove using namespace commands. (#1794)
This CL removes the last two 'using namespace' commands.
2018-08-03 08:05:52 -04:00
dan sinclair
58a6876cee
Rewrite include guards (#1793)
This CL rewrites the include guards to make PRESUBMIT.py include guard
check happy.
2018-08-03 08:05:33 -04:00
dan sinclair
d38a0a3b44
Validation within function body when doing a FunctionCall. (#1790)
When validating a FunctionCall we can trigger an assert if we are not
currently within a function body. This CL adds verification that we are
within a function before attempting to add a function call.

Issue 1789.
2018-08-02 16:58:45 -04:00
Steven Perron
ce644d4a24
Update OpPhi instructions after splitting block. (#1783)
In the merge return pass, we will split a block, but not update the phi
instructions that reference the block.  Since the branch in the original
block is now part of the block with the new id, the phi nodes must be
updated.

This commit will change this.

I have also considered other places where an id of a basic block could
be referenced, and I don't think any of them need to change.

1) Branch and merge instructions: These jump to the start of the
original block, and so we want them to jump to the block that uses the
original id.  Nothing needs to change.

2) Names and decorations: I don't think it matters with block keeps the
name, and there are no decorations that apply to basic blocks.

Fixes #1736.
2018-08-02 11:02:50 -04:00
dan sinclair
a5a5ea0e2d
Remove using std::<foo> statements. (#1756)
Many of the files have using std::<foo> statements in them, but then the
use of <foo> will be inconsistently std::<foo> or <foo> scattered
through the file. This CL removes all of the using statements and
updates the code to have the required std:: prefix.
2018-08-01 14:58:12 -04:00
dan sinclair
ebd6c75a71
Remove diag() overloads. (#1776)
This CL removes the two diag() overloads and leaves only the version
which accepts an Instruction. This is safer as we never use the
implicit location from the validation state.
2018-08-01 14:55:20 -04:00
Steven Perron
c8c724cba7
Don't change decorations and names in merge return. (#1777)
When creating a new phi for a value in the function, merge return will
rewrite all uses of an id that are no longer dominated by its
definition.  Uses that are not in a basic block, like OpName or
decorations, are not dominated, but they should not be replaced.

Fixes #1736.
2018-08-01 13:47:09 -04:00
dan sinclair
2c5f1b01d8
Update diag() calls in validate_cfg. (#1760)
This CL updates the diag() calls in validate_cfg to provide the
associated instruction. This fixes a couple places where we output the
last line of the file instead of the instruction as the disassembly.
2018-08-01 09:52:16 -04:00
dan sinclair
b7afe4e7ae
Switch validate to use explicit diag() method. (#1750)
This CL changes validate.cpp to use diag providing an explicit
instruction. This changes the result of the function end checks to not
output a disassembly anymore as printing the last line of the module
didn't seem to make sense.
2018-07-31 14:53:10 -04:00
Alan Baker
755e5c9420 Transform to combine consecutive access chains
* Combines OpAccessChain, OpInBoundsAccessChain, OpPtrAccessChain and
OpInBoundsPtrAccessChain
* New folding rule to fold add with 0 for integers
 * Converts to a bitcast if the result type does not match the operand
 type
V
2018-07-31 13:42:47 -04:00
Dan Sinclair
f28ed82fd9 Make sure all instructions are in the ordered list.
Currently, some instructions will be missing from the list of
ordered_instructions. This will cause issues due to the debug change
which passed the last instruction into subsequent passes.

This CL moves the addition to the ordered list out of the
RegisterInstruction method into AddOrderedInstruction. This method is
called first in ProcessInstruction and the CapabilitiesPass and IdPass
are updated to take an Instruction parameter.
2018-07-31 09:55:57 -04:00
dan sinclair
dcea11fa03
Update error messages in validate_composites. (#1743)
This CL removes the redundant operator name from the error messages in
validate_composites. The operator will be printed on the next line with
the disassembly.
2018-07-31 09:52:14 -04:00
dan sinclair
dcb0dc21de
Split ImagePass into individual methods. (#1742)
This CL splits the switch in ImagePass into individual validate
functions. The error messages have been updated to drop the
suffix/prefix of the opcode name since it will be displayed in the
disassembly.
2018-07-30 16:59:29 -04:00
dan sinclair
673483d6a7
Move OpVectorShuffle check into validate_composites (#1741)
This CL moves the OpVectorShuffle ID check out of validate_id and into
validate_composites with the rest of the composite checks.
2018-07-30 16:12:49 -04:00
Diego Novillo
99fe61e724 Add API to create passes out of a list of command-line flags.
This re-implements the -Oconfig=<file> flag to use a new API that takes
a list of command-line flags representing optimization passes.

This moves the processing of flags that create new optimization passes
out of spirv-opt and into the library API.  Useful for other tools that
want to incorporate a facility similar to -Oconfig.

The main changes are:

1- Add a new public function Optimizer::RegisterPassesFromFlags. This
   takes a vector of strings.  Each string is assumed to have the form
   '--pass_name[=pass_args]'.  It creates and registers into the pass
   manager all the passes specified in the vector.  Each pass is
   validated internally.  Failure to create a pass instance causes the
   function to return false and a diagnostic is emitted to the
   registered message consumer.

2- Re-implements -Oconfig in spirv-opt to use the new API.
2018-07-27 15:10:08 -04:00
Alan Baker
b49f76fd62 Handle undef literal value in vector shuffle
Fixes #1731

* Updated folding rules related to vector shuffle to account for the
undef literal value:
 * FoldVectorShuffleFeedingShuffle
 * FoldVectorShuffleFeedingExtract
 * FoldVectorShuffleWithConstants
* These rules would commit memory violations due to treating the undef
literal value as an accessible composite component
2018-07-20 11:32:43 -04:00
Alan Baker
3c19651733 Add variable pointer support to IsValidBasePointer
Fixes #1729

* Adds supported opcodes to IsValidBasePointer() enable by
VariablePointers and VariablePointersStorageBuffer capabilities
 * Added tests
2018-07-19 14:43:59 -04:00
Alan Baker
28199b80b7 Fix block ordering in dead branch elim
Fixes #1727

* If the pass finds any dead branches it can optimize then at the end of
the pass it reorders basic blocks to ensure they satisfy block ordering
requirements
 * Added some new tests
* While investigating this issue, found and fixed a non-deterministic
ordering of dominators
 * Now the edges used to construct the dominator tree are sorted
 according to posorder traversal indices
2018-07-19 11:17:57 -04:00
Dan Sinclair
8c7dab5caa Fixup line number for OpVectorShuffle ID error.
This CL updates the code to pull a valid instruction for the line number
when outputting a component error in OpVectorShuffle. The error line
isn't the best at this point as it points at the component, but it's
better then a -1 (turning to max<size_t>) that was being output.

The error messages has been updated to better reflect what the error is
attempting to say.

Issue 1719.
2018-07-16 14:18:53 -04:00
Steven Perron
208921efe8 Fix finding constant with particular type. (#1724)
With current implementation, the constant manager does not keep around
two constant with the same value but different types when the types
hash to the same value. So when you start looking for that constant you
will get a constant with the wrong type back.

I've made a few changes to the constant manager to fix this.  First off,
I have changed the map from constant to ids to be an std::multimap.
This way a single constant can be mapped to mutiple ids each
representing a different type.

Then when asking for an id of a constant, we can search all of the ids
associated with that constant in order to find the one with the correct
type.
2018-07-16 12:36:53 -04:00
Steven Perron
95b4d47e34 Fix infinite loop while folding OpVectorShuffle (#1722)
When folding an OpVectorShuffle where the first operand is defined by
an OpVectorShuffle, is unused, and is equal to the second, we end up
with an infinite loop.  This is because we think we change the
instruction, but it does not actually change.  So we keep trying to
folding the same instruction.

This commit fixes up that specific issue.  When the operand is unused,
we replace it with Null.
2018-07-13 12:43:00 -04:00
Steven Perron
63c1d8fb15
Fix size error when folding vector shuffle. (#1721)
When folding a vector shuffle that feeds another vector shuffle causes
the size of the first operand to change, when other indices have to be
adjusted reletive to the new size.
2018-07-13 11:20:02 -04:00
dan sinclair
e477e7573e
Remove the module from opt::Function. (#1717)
The function class provides a {Set|Get}Parent call in order to provide
the context to the LoopDescriptor methods. This CL removes the module
from Function and provides the needed context directly to LoopDescriptor
on creation.
2018-07-12 14:42:05 -04:00
dan sinclair
a5e4a53217
Remove context() method from opt::Function (#1700)
This CL removes the context() method from opt::Function. In the places
where the context() was used we can retrieve, or provide, the context in
another fashion.
2018-07-12 10:16:15 -04:00
dan sinclair
f96b7f1cb9
use Pass::Run to set the context on each pass. (#1708)
Currently the IRContext is passed into the Pass::Process method. It is
then up to the individual pass to store the context into the context_
variable. This CL changes the Run method to store the context before
calling Process which no-longer receives the context as a parameter.
2018-07-12 09:08:45 -04:00
Lei Zhang
4db9c789ff Add option to skip verifying block layout
We need this to avoid emitting errors on DirectX layout rules.
2018-07-11 18:00:54 -04:00
Steven Perron
e63551deac Add folding rule to merge a vector shuffle feeding another one. 2018-07-11 14:44:46 -04:00
David Neto
2c6185e6bf Enforce block layout rules even when relaxed
- Vulkan 1.0 uses strict layout rules
- Vulkan 1.0 with relaxed-block-layout validator option
  enforces all rules except for the relaxation of vector
  offset.
- Vulkan 1.1 and later always supports relaxed block layout

Add spot check tests for the relaxed-block-layout scenarios.

Fixes #1697
2018-07-11 10:38:36 -04:00
dan sinclair
e70a412609
Move validation files to val/ directory (#1692)
This CL moves the various validate files into the val/ directory with
the rest of the validation infrastructure. This matches how opt/ is
setup with the passes with the infrastructure.
2018-07-11 10:27:34 -04:00
dan sinclair
2cce2c5b97
Move tests into namespaces (#1689)
This CL moves the test into namespaces based on their directories.
2018-07-11 09:24:49 -04:00
David Neto
fec6315fad Vulkan permits non-monotonic offsets for block members
Other environments do not.
Add tests for OpenGL 4.5 and SPIR-V universal 1.0 to ensure
they still check monotonic layout.

For universal 1.0, we're assuming it otherwise follows Vulkan
rules for block layout.

Fixes #1685
2018-07-10 17:16:54 -04:00
dan sinclair
84846b7e76
Cleanup whitespace lint warnings. (#1690)
This CL cleans up the whitespace warnings and enables the check when
running 'git cl presubmit --all -uf'.
2018-07-10 13:09:46 -04:00
Sean Purcell
9532aede29 Fix unused param errors when Effcee not present 2018-07-10 11:57:42 -04:00
dan sinclair
a3e3869540
Convert validation to use libspriv::Instruction where possible. (#1663)
For the instructions which execute after the IdPass check we can provide
the Instruction instead of the spv_parsed_instruction_t. This
Instruction class provides a bit more context (like the source line)
that is not available from spv_parsed_instruction_t.
2018-07-10 10:57:52 -04:00
dan sinclair
43144e36c1
Move the validation code into the val:: namespace (#1682)
This CL moves the validation code to the val:: namespace. This makes it
clearer which instance of the Instruction and other classes are being
referred too.
2018-07-09 23:18:44 -04:00
dan sinclair
e6b953361d
Move the ir namespace to opt. (#1680)
This CL moves the files in opt/ to consistenly be under the opt::
namespace. This frees up the ir:: namespace so it can be used to make a
shared ir represenation.
2018-07-09 11:32:29 -04:00
dan sinclair
3dad1cda11
Change libspirv to spvtools namespace (#1678)
This CL changes all of the libspirv namespace code to spvtools to match
the rest of the code base.
2018-07-07 09:38:00 -04:00
dan sinclair
76e0bde196 Move utils/ to spvtools::utils
Currently the utils/ folder uses both spvutils:: and spvtools::utils.
This CL changes the namespace to consistenly be spvtools::utils to match
the rest of the codebase.
2018-07-06 16:47:46 -04:00
dan sinclair
9836b05acd Move comp code into comp namespace
This CL moves the code in the comp/ directories into the comp namespace.
2018-07-06 16:38:41 -04:00
David Neto
5e0276bdc9 validator: use RowMajor, ArrayStride, MatrixStride
Implement rules for row-major matrices

Use ArrayStride and MatrixStride to compute sizes

Propagate matrix stride and RowMajor/ColumnMajor through array members of structs.

Fixes #1637
Fixes #1668
2018-07-06 13:35:16 -04:00
David Neto
1a283f41ed Layout validation: Permit {vec3; float} tight packing
Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/1666
2018-07-06 13:11:07 -04:00
Alan Baker
c460f44fbc Add a check for invalid exits from case construct.
Fixes #1618.

Adds a check that validates acceptable exits from case constructs. Case
constructs may only exit to another case construct, the corresponding
merge, an outer loop continue or outer loop merge.
2018-07-06 11:52:13 -04:00
David Neto
a069499032 Fix layout checks for StorageBuffer and PushConstant storage classes
Fixes #1664 :  PushConstant with Block follows storage buffer rules
  PushConstant variables were being checked with block rules, which are
  too strict.
Fixes #1606 :  StorageBuffer with Block layout follows buffer rules
  StorageBuffer variables were not being checked before.

Fix layout messages: say storage class and decoration
  We need to provide more information about storage class and decoration.
2018-07-06 11:04:23 -04:00
Steven Perron
a45d4cac61 Move folding routines into a class
The folding routines are currently global functions.  They also rely on
data in an std::map that holds the folding rules for each opcode.  This
causes that map to not have a clear owner, and therefore never gets
deleted.

There has been a request to delete this map.  To implement this, we will
create a InstructionFolder class that owns the maps.  The IRContext will
own the InstructionFolder instance.  Then the global functions will
become public memeber functions of the InstructionFolder.

Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/1659.
2018-07-05 17:52:43 -04:00
Steven Perron
9ecbcf5fc8 Make sure the constant folder get the correct type.
There are a few locations where we need to handle duplicate types.  We
cannot merge them because they may be needed for reflection.  When this
happens we need do some extra lookups in the type manager.

The specific fixes are:

1) When generating a constant through `GetDefiningInstruction` accept
and use an id for the desired type of the constant.  This will make sure
you get the type that is needed.

2) In Private-to-local, make sure we to update the def-use chains when a
new pointer type is created.

3) In the type manager, make sure that `FindPointerToType` returns a
pointer that points to the given type and not a duplicate type.

4) In scalar replacment, make sure the null constants that are created
are the correct type.
2018-07-05 14:34:30 -04:00
David Neto
30a9cefa1d Support SPV_KHR_8bit_storage
- Add asm/dis test for SPV_KHR_8bit_storage
- validator: SPV_KHR_8bit_storage capabilities enable declaration of 8bit int

TODO:
- validator: ban arithmetic on 8bit unless Int8 is enabled
  Covered by https://github.com/KhronosGroup/SPIRV-Tools/issues/1595
2018-07-03 15:53:19 -04:00
dan sinclair
51091045fe
Produce better error diagnostics in the CFG validation. (#1660)
Produce better error diagnostics in the CFG validation.

This CL fixes up several issues with the diagnostic error line output
in the CFG validation code. For the cases where we can determine a
better line it has been output. For other cases, we removed the
diagnostic line and the error line number from the results.

Fixes #1657
2018-07-03 15:06:54 -04:00
Steven Perron
465f2815cb Revert change and stop running remove duplicates.
Revert "Don't merge types of resources"

This reverts commit f393b0e480, but leaves
the tests that were added.  Added new test. These test are the so that,
if someone tries the same change I made, they will see the test that
they need to handle.

Don't run remove duplicates in -O and -Os

Romve duplicates was run to help reduce compile time when looking for
types in the type manager.  I've run compile time test on three sets
of shaders, and the compile time does not seem to change.

It should be safe to remove it.
2018-06-29 14:09:44 -04:00
Steven Perron
2eb9bfb5b6 Remove stores of undef.
When storing an undef, any value is valid, including the one already in
that memory location.  So we can avoid the store.
2018-06-29 09:49:19 -04:00
David Neto
b67beca723 GLSL.std.450 Refract Eta can be any float scalar
This is a decision from Khronos-internal SPIR-V spec issue 337.
2018-06-28 16:12:21 -04:00
Greg Roth
7cc9f36283 Add test for CFG alteration by compact IDs
The Compact IDs pass can corrupt the CFG, but first the CFG has to
be setup. To do this, a test that builds the CFG, then performs the
compact IDs pass, then checks context consistency.

Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/1648
2018-06-28 08:48:34 -06:00
Steven Perron
f393b0e480 Don't merge types of resources
When doing reflection users care about the names of the variable, the
name of the type, and the name of the members.  Remove duplicates breaks
this because it removes the names one of the types when merging.

To fix this we have to keep the different types around for each
resource.  This commit adds code to remove duplicates to look for the
types uses to describe resources, and make sure they do not get merged.

However, allow merging of a type used in a resource with something not
used in a resource.  Was done when the non resource type came second.

This could have a negative effect on compile time, but it was not
expected to be much.

Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/1372.
2018-06-27 13:57:07 -04:00
David Neto
c2e3e67c31 validator: Fix storage buffer layout message 2018-06-27 09:54:40 -04:00
David Neto
8ecd833dbc Block-decorated structs must list members in offset-order
Additionally, implmentes code review feedback.

Adds more detailed messages for Block and BufferBlock layout errors.

Fixes #1638
2018-06-26 23:31:00 -04:00
Ari Suonpaa
29923409e9 Add validation for structs decorated as Block or BufferBlock.
Fixes #937

Stop std140/430 validation when runtime array is encountered.

Check for standard uniform/storage buffer layout instead of std140/430.

Added validator command line switch to skip block layout checking.

Validate structs decorated as Block/BufferBlock only when they
are used as variable with storage class of uniform or push
constant.

Expose --relax-block-layout to command line.

dneto0 modification:
- Use integer arithmetic instead of floor.
2018-06-26 14:23:18 -04:00
Alan Baker
0d43e10b4a Use type id when looking up vector type
Fixes #1634

* Vector components of composite constructs used wrong accessor
2018-06-25 09:47:29 -04:00
David Neto
4d99fcba9d Validator test: artificially lower limit on local var limit
We need this to reduce the test time on Visual Studio debug builds.
AppVeyor times out at 300s for a process.

Artificially lower the local variable limit check for testing purposes.
We don't get much value from using the full 500K+ variables.
Use a limit of 5000 instead.

Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/1632
2018-06-21 17:08:49 -04:00
Corentin Wallez
ba602c9059 Add a WIP WebGPU environment. It disallows OpUndef
Add SPV_ENV_WEBGPU_0 for work-in-progress WebGPU.

val: Disallow OpUndef in WebGPU env

Silence unused variable warnings when !defined(SPIRV_EFFCE)

Limit visibility of validate_instruction.cpp's symbols
  Only InstructionPass needs to be visible so all other functions are put
  in an anonymous namespace inside the libspirv namespace.
2018-06-21 15:53:15 -04:00
Alan Baker
e7ace1b280 Add Vulkan 1.1 capability sets
Fixes #1597

* Classifies useable capabilities for Vulkan 1.1
* Updates tests
2018-06-21 14:12:02 -04:00
David Neto
8d65c89678 Instruction lookup succeeds if it's enabled by a capability
Also add a corresponding check for capabilities in the validator.

Update previously existing test cases where an instruction used to fail
assembling because of a version check, but now they succeed because the
instruction is also guarded by a capability.  Now it should assemble.
Add tests to ensure that capabilities are checked appropriately.

The explicitly reserved instructions OpImageSparseSampleProj*
now assemble, but they fail validation.

Fixes #1624
2018-06-20 10:44:03 -04:00
dan sinclair
f80696eaf6
[val] Add extra context to error messages. (#1600)
[val] Add extra context to error messages.

This CL extends the error messages produced by the validator to output the
disassembly of the errored line.

The validation_id messages have also been updated to print the line number of
the error instead of the word number. Note, the error number is from the start
of the SPIR-V, it does not include any headers printed in the disassembled code.

Fixes #670, #1581
2018-06-19 16:02:44 -04:00
dan sinclair
c4304ea0ac Reland "Disallow array-of-arrays with DescriptorSets when validating. (#1586)"
This CL reverts the revert of 'Disallow array-of-arrays with DescriptorSets when
validating." Other changes have been committed which should aleviate the
AppVeryor resource constraints.

This reverts commit f2c93c6e12.

This CL adds validation to disallow using an array-of-arrays when attached to a
DescriptorSet.

Fixes #1522
2018-06-19 15:14:17 -04:00
dan sinclair
d3ed998222
Validate Ids before DataRules. (#1622)
Validate Ids before DataRules.

The DataRule validators call FindDefs with the assumption that they
definitions being looked at can be found. This may not be true if we
have not validated identifiers first.

This CL flips the IdPass and DataRulesPass to fix this issue.
2018-06-19 09:32:20 -04:00
Alan Baker
ea7239fa73 Structured switch checks
Fixes #491

* Basic blocks now have a link to the terminator
* Check all case sepecific rules
* Missing check for branching into the middle of a case (#1618)
2018-06-13 15:04:47 -04:00
Alan Baker
4f866abfd8 Validate static uses of interfaces
Fixes #1120

Checks that all static uses of the Input and Output variables are listed
as interfaces in each corresponding entry point declaration.
 * Changed validation state to track interface lists
 * updated many tests
* Modified validation state to store entry point names
 * Combined with interface list and called EntryPointDescription
 * Updated uses
* Changed interface validation error messages to output entry point name
in addtion to ID
2018-06-13 10:56:14 -04:00
Steven Perron
1f7b1f1bf7 Small vector optimization for operands.
We replace the std::vector in the Operand class by a new class that does
a small size optimization.  This helps improve compile time on Windows.

Tested on three sets of shaders.  Trying various values for the small
vector.  The optimal value for the operand class was 2.  However, for
the Instruction class, using an std::vector was optimal.  Size of "0"
means that an std::vector was used.

                Instruction size
	        0      4      8
Operand Size

0               489    544    684
1               593    487
2               469    570
4               473
8               505

This is a single thread run of ~120 shaders.  For the multithreaded run
the results were the similar.  The basline time was ~62sec.  The
optimal configuration was an 2 for the OperandData and an
std::vector for the OperandList with a compile time of ~38sec.  Similar
expiriments were done with other sets of shaders.  The compile time still
improved, but not as much.

Contributes to https://github.com/KhronosGroup/SPIRV-Tools/issues/1609.
2018-06-12 13:41:08 -04:00
David Neto
700ebd3442 Make fewer test executables
Try to reduce the amount of disk space used by especially by debug builds,
which may be contributing to AppVeyor failures.

Collapses tests in categories:
- validator
- loop optimizations
- dominator analysis
- linker

Contributes to #1615
2018-06-12 09:48:42 -04:00
David Neto
363bfca2ed Operand lookup succeeds if it's enabled by a capability
- Fix tests for basic group operations (e.g. Reduce) to allow for
new capabilities in SPIR-V 1.3 that enable them.
- Refactor operand capability check to avoid code duplication and
to put all checks that don't need table lookup before any table
lookup.
- Test round trip assembly/disassembly support for extension
SPV_NV_viewport_array2
- Test assembly and validation of decoration ViewportRelativeNV

Fixes #1596
2018-06-11 19:27:52 -04:00
Alan Baker
06de86863b Check for invalid branches into construct body.
Fixes #1281

* New structured cfg check: all non-construct header blocks'
predecessors must come from within the construct
* New function to calculate blocks in a construct

* Fixed a bug in BasicBlock type bitset

Relaxing check to not consider unreachable predecessors

* Fixing broken common uniform elim test
2018-06-11 19:23:44 -04:00
dan sinclair
63c9bba59d
[val] Output id names along with numbers in validate_id (#1601)
This CL updates the validate_id code to output the name of the object along with
the id number. There were a few instances which already output the name, this
just extends to all of them. Now, the output should say 123[obj] instead of just
123.

Issue #1581
2018-06-06 22:08:27 -04:00
dan sinclair
f2c93c6e12
Revert "Disallow array-of-arrays with DescriptorSets when validating. (#1586)" (#1607)
This reverts commit e3f1f3bda5.
2018-06-06 20:27:43 -04:00
dan sinclair
e3f1f3bda5
Disallow array-of-arrays with DescriptorSets when validating. (#1586)
* Disallow array-of-arrays with DescriptorSets when validating.

This CL adds validation to disallow using an array-of-arrays when attached to a
DescriptorSet.

Fixes #1522
2018-06-05 09:11:35 -04:00
Steven Perron
fe2fbee294 Delete the insert-extract-elim pass.
Replaces anything that creates an insert-extract-elim pass and create
a simplifiation pass instead.  Then delete the implementation of the
pass.

Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/1570.
2018-06-01 10:13:39 -04:00
Steven Perron
9a008835f4 Add store for var initializer in inlining.
Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/1591.
2018-06-01 09:44:42 -04:00
Alan Baker
badcf73d00 Allow duplicate pointer types
Fixes #1577

* Remove validation requiring unique pointer types unless variable
pointers extension enabled
* Modified scalar replacement to always look for an undecorated pointer
2018-05-31 09:14:38 -04:00
Steven Perron
93c4c184d5 Handle types with self references.
By using forward pointers, we are able to define a struct that has a
pointer to itself.  This could be directly or indirectly.  The current
implementation of the type manager did not handle this case.  There are
three changes that are made in this commit inorder to handle this case:

1) Change the handling of OpTypeForwardPointer

The current handling of OpTypeForwardsPointer is broken if there is a
reference to the pointer before the real definition.  When build the
type that contain the forward delared pointer, the type manager will ask
for the type for that ID, and will get a nullptr because it does not
exists.  This nullptr is not handleded very well.

The change is to keep track of the incomplete types the first time
through all of the types.  An incomplete type is a ForwardPointer or any
type that references an incomplete type.

Then we implement a second pass through the incomplete types that will
complete them.

2) Hashing types.

When hashing a type, we want to uses all of the subtypes as part of the
hash.  However, with types that reference them selves, this creates an
infinite recursion.  To get around this, we keep track of which types
have been seen on the path from the root type.  If we have see the
current type already then we can stop the recursion.

3) Comparing types.

In order to check if two types are the same, we must check that all of
their subtypes are the same as well.  This also causes an infinit
recursion.  The solution is to stop comparing the subtypes if we are
trying to compare two pointer types that we are already in the middle of
comparing.  The ideas is that if the two pointer are different, then in
progress compare will return false itself.

Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/1578.
2018-05-30 15:48:38 -04:00
Steven Perron
745dd00af9 Fold FMix feeding Extract, and use the simplification pass.
We add a new rule to the folding rules to fold an FMix feeding an
extract when the alpha value for the element being extracted is either
0 or 1.  In those case, we can simple extract from one of the operands
to the FMix.

With that change the simplification pass completely subsumes the
insert-extract elimination pass.  So we remove the insert-extract
elimination passes and replce them with calls to the simplification
pass.

In a follow up PR, we should delete the insert-extract elimination pass.

Contributes to https://github.com/KhronosGroup/SPIRV-Tools/issues/1570.
2018-05-25 14:42:59 -04:00
dan sinclair
0a14a1f748 Validate that only a single OpMemoryModel is provided.
This CL adds validation that only a single OpMemoryModel is provided in the
SPIR-V binary.

Fixes #1574
2018-05-24 08:43:14 -04:00
dan sinclair
3b87dac56b Validate presence of OpMemoryModel.
According to the SPIR-V Spec, section 2.4 Logical Layout of a Module there
should be a single required OpMemoryModel instruction provided. This CL adds
validation that OpMemoryModel is provided to the SPIR-V validator.

Fixes #1207
2018-05-23 08:17:39 -04:00
Steven Perron
a579e720a8 Remove the limit on struct size in SROA.
Removes the limit on scalar replacement for the lagalization passes.
This is done by adding an option to the pass (and command line option)
to set the limit on maximum size of the composite that scalar
replacement is willing to divide.

Fixes #1494.
2018-05-18 10:03:46 -04:00
Steven Perron
f1f7cc870e Get ADCE to handle OpCopyMemory
ADCE does not treat OpCopyMemory as an instruction that references
memory.  Because of that stores are removed that should not be.

This change teaches ADCE that OpCopyMemory and OpCopyMemorySize both
loads from and stores to memory.  This will keep other stores live when
needed, and will allows ADCE to remove OpCopyMemory instructions as
well.

Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/1556.
2018-05-16 13:50:47 -04:00
Lei Zhang
b09e3ce842
Allow ViewportIndex & Layer to be used in VS/DS with extension
SPV_EXT_shader_viewport_index_layer enables using ViewportIndex
and Layer in vertex and tessellation shaders.

Also, as per the Vulkan spec:

> The ViewportIndex decoration must be used only within vertex,
> tessellation evaluation, geometry, and fragment shaders.

> In a vertex, tessellation evaluation, or geometry shader, any
> variable decorated with ViewportIndex must be declared using
> the Output storage class.

> In a fragment shader, any variable decorated with ViewportIndex
> must be declared using the Input storage class.

Similarly for Layer.
2018-05-16 13:16:27 -04:00
Steven Perron
9b1a938ea1 SROA: Only create symbols that are loaded.
Currently in scalar replacement, we create a new variable for every
memeber of the composite being divided.  It is often overkill, because
not all of those members will be used.  This change will check which
elements are used and only create variable for the members that are
used.

This reduces the compile time for one set of shader from 248s to 165s.

Part of https://github.com/KhronosGroup/SPIRV-Tools/issues/1494.
2018-05-16 10:48:25 -04:00
Steven Perron
0e1b7e5aef Fix getting operand without checking opcode.
Fixes https://github.com/KhronosGhttps://github.com/KhronosGroup/SPIRV-Tools/issues/1559roup/SPIRV-Tools/issues/1559.

There is an load of an operand of an instruction that was suppose to be
only for the OpCompositeExtract case.  However, an error caused it to
be loaded for every opcode, even those that do not have an operand in
that position.

We fix up that bug, and a couple other things noticed that the same
time.
2018-05-16 09:34:43 -04:00
Lei Zhang
efcc33e8a9
Support SpvOpExecutionModeId in SPIR-V logical layout 2018-05-16 08:43:50 -04:00
alan-baker
18ad1be7f9 Fixing MacOS compiler error 2018-05-15 12:23:27 -04:00
Steven Perron
f46f2d3e5d Remove redundant stores.
The code patterns generated by DXC around function calls can cause many
store to be storing the same value that was just loaded from the same
location:

```
%10 = OpLoad %type %var
OpStore %var %10
```

We want to clean these up very early on because they can cause other
transformations to do a lot of work.  For the cases I see, they can be
removed during local-single-block-elim.

For one set of shaders the compile time goes from 248s to 182s.  A 26%
improvement.

Part of https://github.com/KhronosGroup/SPIRV-Tools/issues/1494.
2018-05-15 10:24:05 -04:00
Steven Perron
af430ec822 Add pass to fold a load feeding an extract.
We have already disabled common uniform elimination because it created
sequences of loads an entire uniform object, then we extract just a
single element.  This caused problems in some drivers, and is just
generally slow because it loads more memory than needed.

However, there are other way to get into this situation, so I've added
a pass that looks specifically for this pattern and removes it when only
a portion of the load is used.

Fixes #1547.
2018-05-14 15:40:34 -04:00
Steven Perron
804e8884c4 Fold fclamp feeding compare.
An FClamp instruction forces a values to be within a certain interval.
When the upper or lower bound of the FClamp is a constant and the value
being compared with is a constant, then in some case we can fold the
compared because the entire range is say less than the value.

Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/1549.
2018-05-14 10:27:49 -04:00
Lei Zhang
e9cda70261 Adjust tests according to grammar change
* ConstOffsets now requires ImageGatherExtended
* Int8 does not require Kernel anymore
2018-05-10 16:32:59 -04:00
Steven Perron
9ec3f81e5c Remove dead Workgroup variables in ADCE.
If there is a shader with a variable in the workgroup storage class that
is stored to, but not loadeds, then we know nothing will read those
loads.  It should be safe to remove them.

This is implemented in ADCE by treating workgroup variables the same
way that private variables are treated.

Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/1550.
2018-05-09 16:07:26 -04:00
Steven Perron
7d01643132 Allow hoisting code in if-conversion.
When doing if-conversion, we do not currently move code out of the side
nodes.  The reason for this is that it can increase the number of
instructions that get executed because both side nods will have to be
executed now.

In this commit, we add code to move an instruction, and all of the
instructions it depends on, out of a side node and into the header of
the selection construct.  However to keep the cost down, we only do it
when the two values in the OpPhi node compute the same value.  This way
we have to move only one of the instructions and the other becomes
unused most of the time.  So no real extra cost.

Makes the value number table an alalysis in the ir context.

Added more opcodes to list of code motion safe opcodes.

Fixes #1526.
2018-05-04 12:56:29 -04:00
Stephen McGroarty
1c2cbaf569 Add GetContinueBlock to loop class.
Previously, the loop class used the terms latch and continue block
interchangeably. This patch splits the two and corrects and tests some
uses of the old uses of GetLatchBlock.
2018-05-03 14:30:41 -04:00
Steven Perron
70bb3c1cc2 Fold divide and multiply by same value.
We want to fold code like (x*y)/x and other permutations of this.

Fixes #1531.
2018-05-02 10:18:37 -04:00
Toomas Remmelg
1dc2458060 Add a loop fusion pass.
This pass will look for adjacent loops that are compatible and legal to
be fused.

Loops are compatible if:

- they both have one induction variable
- they have the same upper and lower bounds
    - same initial value
    - same condition
- they have the same update step
- they are adjacent
- there are no break/continue in either of them

Fusion is legal if:

- fused loops do not have any dependencies with dependence distance
  greater than 0 that did not exist in the original loops.
- there are no function calls in the loops (could have side-effects)
- there are no barriers in the loops

It will fuse all such loops as long as the number of registers used for
the fused loop stays under the threshold defined by
max_registers_per_loop.
2018-05-01 15:40:37 -04:00
Stephen McGroarty
9a5dd6fe88 Support loop fission.
Adds support for spliting loops whose register pressure exceeds a user
provided level. This pass will split a loop into two or more loops given
that the loop is a top level loop and that spliting the loop is legal.
Control flow is left intact for dead code elimination to remove.

This pass is enabled with the --loop-fission flag to spirv-opt.
2018-05-01 15:15:10 -04:00
Steven Perron
9ba0879ddf Improve Vector DCE
Track live scalars in VDCE as if they were single element vectors.

Handle the extended instructions for GLSL in VDCE.

Handle composite construct instructions in VDCE.
2018-04-30 11:55:50 -04:00
Steven Perron
a00a0a09ae Revert "Improvements to vector dce."
This reverts commit 2813722993.

A regression was found.  Undoing the change until it is fixed.
2018-04-27 10:33:19 -04:00
Alan Baker
4246abdc74 Fixes handling of kill and unreachable ops in inlining.
Fixes #1527

* Adds handling for copying OpKill and OpUnreachable and forces the
generation of a new basic block
* Adds tests to check
2018-04-27 09:42:37 -04:00
Steven Perron
e1bcd2b2d8 Fold OpVectorTimesScalar and OpPhi better.
If one of the operands to an OpVectorTimesScalar instruction is zero,
then the result will be the 0 vector. Currently we do not fold the
insturction unless both operands are constants. This change fixes that.

We also allow folding of OpPhi instructions where the incoming values
are either an OpUndef or the OpPhi instruction itself. As with other
cases, this can be simplified to the OpUndef.
2018-04-26 12:41:16 -04:00
Steven Perron
2813722993 Improvements to vector dce.
Track live scalars in VDCE as if they were single element vectors.

Handle the extended instructions for GLSL in VDCE.

Handle composite construct instructions in VDCE.

Fixes #1511.
2018-04-26 11:07:48 -04:00
Greg Fischer
268be6143d LocalSingleBlockElim: Add store-store elimination
Eliminate unused store to variable if followed by store to same
variable in same block.

Most significantly, this cleans up stores made unused by this pass.
These useless stores can inhibit subsequent optimizations, specifically
LocalSingleStoreElim. Eliminating them makes subsequent optimization more
effective.

The main effect of this pass is to simplify the work done by the SSA
rewriter.  It catches many local loads/stores that help speeding up the
work done by the main rewriter.
2018-04-25 10:30:18 -04:00
Steven Perron
2c0ce87210
Vector DCE (#1512)
Introduce a pass that does a DCE type analysis for vector elements
instead of the whole vector as a single element.

It will then rewrite instructions that are not used with something else.
For example, an instruction whose value are not used, even though it is
referenced, is replaced with an OpUndef.
2018-04-23 11:13:07 -04:00
David Neto
7a59283587 Another fix for old XCode: std::set explicit ctor in test code 2018-04-20 15:58:01 -04:00
Victor Lomuller
efc5061929 Dominator analysis interface clean.
Remove the CFG requirement when querying a dominator/post-dominator from an IRContext.

Updated all uses of the function and tests.
2018-04-20 15:41:59 -04:00
Jaebaek Seo
48802bad72 Constant folding for OpVectorTimesScalar 2018-04-20 13:43:04 -04:00
Victor Lomuller
0ec08c28c1 Add register liveness analysis.
For each function, the analysis determine which SSA registers are live
at the beginning of each basic block and which one are killed at
the end of the basic block.

It also includes utilities to simulate the register pressure for loop
fusion and fission.

The implementation is based on the paper "A non-iterative data-flow
algorithm for computing liveness sets in strict ssa programs" from
Boissinot et al.
2018-04-20 09:45:15 -04:00
Alan Baker
09c206b6fb Fixes #1480. Validate group non-uniform scopes.
* Adds new pass for validating non-uniform group instructions
 * Currently on checks execution scope for Vulkan 1.1 and SPIR-V 1.3
* Added test framework
2018-04-20 09:25:00 -04:00
GregF
1c89da46ff Test/DependencyAnalysis: Fix uninitialized variables 2018-04-19 15:34:15 -04:00
Jaebaek Seo
430a29335e Fix broken pointer of CommonUniformElimPass 2018-04-19 09:36:10 -04:00
Steven Perron
c20a718e00 Rewrite local-single-store-elim to not create large data structures.
The local-single-store-elim algorithm is not fundamentally bad.
However, when there are a large number of variables, some of the
maps that are used can become very large.  These large data structures
then take a very long time to be destroyed.  I've seen cases around 40%
if the time.

I've rewritten that algorithm to not use as much memory.  This give a
significant improvement when running a large number of shader through
DXC.

I've also made a small change to local-single-block-elim to delete the
loads that is has replaced.  That way local-single-store-elim will not
have to look at those.  local-single-store-elim now does the same thing.

The time for one set goes from 309s down to 126s.  For another set, the
time goes from 102s down to 88s.
2018-04-18 16:38:18 -04:00
Jaebaek Seo
0fa42996b5
Merge pull request #1461 from jaebaek/fnegate
Add constant folding for OpFNegate

Contributes to #709
2018-04-18 13:46:10 -04:00
Jaebaek Seo
3c5bd26668 Typo 2018-04-17 14:13:19 -04:00
Toomas Remmelg
0f335cf87e Add support for MIV and Delta test dependence analysis.
GCD MIV test as described in Chapter 3 of "Optimizing Compilers for
Modern Architectures: A Dependence-Based Approach" by Randy Allen, and
Ken Kennedy.

Delta test as described in Figure 3 of "Practical Dependence Testing" by
Gina Goff, Ken Kennedy, and Chau-Wen Tseng from PLDI '91.
2018-04-17 13:57:02 -04:00
Jaebaek Seo
ff92339fff Format 2018-04-17 12:12:48 -04:00
Jaebaek Seo
d8b9306a4f Add more unit tests 2018-04-17 12:08:45 -04:00
Jaebaek Seo
79491259e0 Add constant folding for FNegate 2018-04-17 12:08:45 -04:00
Alan Baker
38359ba800 Fixes #1483. Validating Vulkan 1.1 barrier execution scopes
* Reworked how execution model limitations are checked
 * Now OpFunction checks which entry points call it and checks its
 registered limitations instead of building a call stack in the entry
 point
* New tests
* Moving function to entry point mapping into VState
2018-04-17 10:26:38 -04:00
David Neto
152b9a681e ADCE: Remove OpDecorateStringGOOGLE
Also fix a few failures to set "modified" status when removing
global values.

Add OpDecorateStringGOOGLE to decoration ordering

Fixes #1492
2018-04-17 10:24:30 -04:00
Alan Baker
0e80b86dbe Fixes #1472. Per-vertex variable validation fixes.
Relaxs checks for per-vertex builtin variables. If the builtin
decoration is applied to a variable, then those checks now allow a level
of arraying on the variable before checking the type consistency.

* Allows arrays of variables to be present for the per-vertex variables:
 * Position
 * PointSize
 * ClipDistance
 * CullDistance
* Updated tests
2018-04-16 12:58:35 -04:00
Rex Xu
7fe186476a Fix validation issues relevant to SPV_AMD_gpu_shader_int16.
Frexp/FrexpStruct allows exp to be either 16-bit or 32 bit integer if
SPV_AMD_gpu_shader_int16 is enabled.
2018-04-16 10:49:01 -04:00
David Neto
e8814be732 Add validator test for OpBranch
Add test for case where OpBranch branches to a value (a function value).
Previous tests only checked a label value (name of a block.).

Update validate_id.cpp to remove the TODO for OpBranch and say that it
is already checked in validate_cfg.cpp
2018-04-16 10:27:51 -04:00
Steven Perron
d42f65e7c1 Use a bit vector in ADCE
The unordered_set in ADCE that holds all of the live instructions takes
a very long time to be destroyed.  In some shaders, it takes over 40% of
the time.

If we look at the unique ids of the live instructions, I believe they
are dense enough make a simple bit vector a good choice for to hold that
data.  When I check the density of the bit vector for larger shaders, we
are usually using less than 4 bytes per element in the vector, and
almost always less than 16.

So, in this commit, I introduce a simple bit vector class, and
use it in ADCE.

This help improve the compile time for some shaders on windows by the
40% mentioned above.

Contributes to https://github.com/KhronosGroup/SPIRV-Tools/issues/1328.
2018-04-13 16:38:02 -04:00
Alan Baker
e805d1f8d7 Fixes #1469. Allow subgroup memory scope for Vulkan 1.1
* New error that prevents CrossDevice memory scope for all vulkan
* Old error specifically references Vulkan 1.0
* New tests
2018-04-12 13:16:04 -04:00
Alan Baker
c522b697bf Fixes #1470. Don't restrict WGS storage class
* Removed restriction that workgroup size can only be on Input storage
class
* added test
2018-04-12 09:22:34 -04:00
Victor Lomuller
10e5d7cf13 Add a loop peeling pass.
For each loop in a function, the pass walks the loops from inner to outer most loop
and tries to peel loop for which a certain amount of iteration can be done before or after the loop.

To limit code growth, peeling will not happen if the growth in code size goes above a configurable threshold.
2018-04-11 15:41:29 +01:00
Alexander Johnston
61b50b3bfa ZIV and SIV loop dependence analysis.
Provides functionality to perform ZIV and SIV dependency analysis tests
between a load and store within the same loop.

Dependency tests rely on scalar analysis to prove and disprove dependencies
with regard to the loop being analysed.

Based on the 1990 paper Practical Dependence Testing by Goff, Kennedy, Tseng

Adds support for marking loops in the loop nest as IRRELEVANT.
Loops are marked IRRELEVANT if the analysed instructions contain
no induction variables for the loops, i.e. the loops induction
variable is not relevent to the dependence of the store and load.
2018-04-11 09:32:42 -04:00
Steven Perron
53bc1623ec Fold OpDot
Adding three rules to fold OpDot (implemented as two).

- When an OpDot has two constants, then fold to the resulting const.

- When one of the inputs is the 0 vector, then fold to zero.

- When one of the inputs is a single 1 with 0s, then rewrite to an
OpCompositeExtract of the appropriate element.  This will help find
even more folding opportunities.

Contributes to #709.
2018-04-10 13:09:37 -04:00
Alan Baker
3020104ff2 Adding tests for OpenCL 1.2 and embedded profiles 2018-04-09 09:02:50 -04:00
Alan Baker
42840d15e4 Fixes #1433. Validate binary version
* Validates SPIR-V binary version against target environment
2018-04-06 22:41:50 -04:00
Lei Zhang
26a698c347 Fix PrimitiveId builtin check for Vulkan
According to Vulkan spec 1.1.72:

> The PrimitiveId decoration must be used only within fragment,
> tessellation control, tessellation evaluation, and geometry shaders.

> In a tessellation control or tessellation evaluation shader, any
> variable decorated with PrimitiveId must be declared using the Input
> storage class.

We were enforcing that PrimitiveId can only be used with Output
storage class for TCS and TES before.
2018-04-06 22:38:32 -04:00
GregF
6fbfe1c016 Fix SSA rewrite for nested loops.
From the test case, the slice of the CFG that is interesting for the bug
is

25
|
v
30
|
v
31<-+
|   |
v   |
34--+

1. In block 25, we have a Phi candidate for %f with arguments
   %47 = Phi[%float_0, %0]. This merges %float_0 and a yet unknown
   argument from the external loop backedge.
2. We are now processing block 34:
   i. The load %35 = OpLoad %f triggers a Phi candidate to be placed in
      block 31.
  ii. The Phi candidate %50 = Phi needs two arguments. The one coming
      from block 30 is %47. But the one coming from block 34 (which we
      are now processing and have marked sealed), finds %50 itself as
      the reaching def for %f.
3. This wrongfully marks %50 as a copy-of Phi, which ultimately makes
   both %47 and %50 copy-of Phis that get eliminated.
2018-04-06 15:17:52 -04:00
David Neto
e025145c5d Test asm/dis support for SPV_EXT_descriptor_indexing 2018-04-06 13:33:34 -04:00
David Neto
6f80608b8a Test asm/dis support for SPV_NV_shader_subgroup_partitioned 2018-04-06 13:33:24 -04:00
Alan Baker
e66e305b46 Re-enabled checks for UConvert 2018-04-06 10:51:57 -04:00
Pierre Moreau
caf7da87e1 linker: Properly remove FuncParamAttr from imported symbols
Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/898
2018-04-06 09:55:54 -04:00
David Neto
082b8b08f1 More automatic extension support
Update grammar table generation:
- Get extensions from instructions, not just operand-kinds
- Don't explicitly list extensions that come from the SPIR-V core
  grammar or from a KHR extended instruction set grammar.

This makes it easier to support new extensions since the recommended
extension strategy is to add instructions to the core grammar file.

Also, test the validator has trivial support for passing through
the extensions SPV_NV_shader_subgroup_partitioned and
SPV_EXT_descriptor_indexing.
2018-04-05 18:36:08 -04:00
Lei Zhang
43ca2112b8 Stop asking for extensions if feature avaiable in core SPIR-V
Migrating to unified grammar means we sometimes have two fields
for a certain feature: version and extensions. It means the feature
in question can be used either in SPIR-V of advanced-enough
versions or in any SPIR-V with with the specified extensions.

Validator now respects the above rules.
2018-04-05 15:14:07 -04:00
Andrey Tuganov
d7fff408e3 Fix bug validate_builtins (additional def checks)
At every definition of a builtin id, run at-reference-check rules on the
defining instruction as well.

Previosly the validation was missing the case when invalid storage class
was defined in the instruction which defines the built-in, and not in
the instruction which references the built-in.
2018-04-05 13:55:18 -04:00
Andrey Tuganov
691eed92cb Fix major bug in validate_builtins
Fixed an early return in the loop, resulting in only one decoration
being checked.
2018-04-05 13:45:45 -04:00
Andrey Tuganov
da332cf332 Execution mode/model available in validation state
Refactored validate built-ins to make
GetExecutionModels(entry_point)
and
GetExecutionModes(entry_point)
available in validation state.

Entry points are allowed to have multiple execution modes and execution
models.

Finished the last missing feature in Vulkan built-ins validation:
FragDepth requires DepthReplacing.
2018-04-05 11:55:42 -04:00
Steven Perron
742454968d OpName and decorations should not stop array copy prop. 2018-04-04 22:24:10 -04:00
Steven Perron
7c5d49bf2a Teach ADCE about OpImageTexelPointer
Currently OpImageTexelPointer operations are treat like a use of the
pointer, but it does
not look for the memory being referenced to make sure stores are not
removed.

This change teaches it so identify the memory being accessed, and
treats it as if that memory is loaded.

Fixes to #1445.
2018-04-04 13:45:29 -04:00
Steven Perron
c33af63264 Teach array copy propagation about OpImageTexelPointer.
OpImageTexelPointer acts like a special kind of load.  It is not an
array load, but it also cannot be removed the same way a regular
load can.  The type of propagation that needs to be done is similar
to what we do for arrays, so I want to merge that code into that
optmization.

Contributers to #1445.
2018-04-04 13:42:51 -04:00
Steven Perron
e64a4656b3 Teach the private to local about OpImageTexelPointer.
OpImageTexelPointer acts like a special kind of load.  It is still
safe to change the storage class of a variable used in a
OpImageTexalPointer instruction.

Contributes to #1445.
2018-04-04 13:42:35 -04:00
Neil Roberts
57a2441791 hex_float: Use max_digits10 for the float precision
CPPreference.com has this description of digits10:

“The value of std::numeric_limits<T>::digits10 is the number of
 base-10 digits that can be represented by the type T without change,
 that is, any number with this many significant decimal digits can be
 converted to a value of type T and back to decimal form, without
 change due to rounding or overflow.”

This means that any number with this many digits can be represented
accurately in the corresponding type. A change in any digit in a
number after that may or may not cause it a different bitwise
representation. Therefore this isn’t necessarily enough precision to
accurately represent the value in text. Instead we need max_digits10
which has the following description:

“The value of std::numeric_limits<T>::max_digits10 is the number of
 base-10 digits that are necessary to uniquely represent all distinct
 values of the type T, such as necessary for
 serialization/deserialization to text.”

The patch includes a test case in hex_float_test which tries to do a
round-robin conversion of a number that requires more than 6 decimal
places to be accurately represented. This would fail without the
patch.

Sadly this also breaks a bunch of other tests. Some of the tests in
hex_float_test use ldexp and then compare it with a value which is not
the same as the one returned by ldexp but instead is the value rounded
to 6 decimals. Others use values that are not evenly representable as
a binary floating fraction but then happened to generate the same
value when rounded to 6 decimals. Where the actual value didn’t seem
to matter these have been changed with different values that can be
represented as a binary fraction.
2018-04-03 12:53:10 -04:00
Lei Zhang
fc9f621e8b Add missing <iterator> header for std::back_inserter 2018-03-30 11:30:25 -04:00
Steven Perron
cbceeceab4 In copy-prop-arrays, indentify copies via OpCompositeInsert
When the original code copies an entire array or struct one element at a
time, this turns into a series of OpCompositeInsert instruction followed
by a store of the whole array.  We currently miss opportunities in copy
propagate arrays because we do not recognize this as a copy.

This commit adds code to copy propagate arrays to identify this code
pattern.

Also updates the performance passed to run array copy propagation.
2018-03-29 09:39:55 -04:00
Steven Perron
d8ca09821d Handle non-constant accesses in memory objects (copy prop arrays)
The first implementation of MemroyObject, which is used in copy
propagate arrays, forced the access chain to be like the access chains
in OpCompositeExtract.  This excluded the possibility of the memory
object from representing an array element that was extracted with a
variable index.   Looking at the code, that restriction is not
neccessary.  I also see some opportunities for doing this in some real
shaders.

Contributes to #1430.
2018-03-28 20:23:47 -04:00
Stephen McGroarty
ad7e4b8401 Initial patch for scalar evolution analysis
This patch adds support for the analysis of scalars in loops. It works
by traversing the defuse chain to build a DAG of scalar operations and
then simplifies the DAG by folding constants and grouping like terms.
It represents induction variables as recurrent expressions with respect
to a given loop and can simplify DAGs containing recurrent expression by
rewritting the entire DAG to be a recurrent expression with respect to
the same loop.
2018-03-28 16:34:23 -04:00
Alan Baker
0a2ee65f57 Fixes #1403.
Don't validate composite insert, extract and construct instructions
against spec constant sized arrays.
* Added predicate for spec constant opcodes
* Added tests
2018-03-28 09:04:08 -04:00
Alan Baker
97c8fdccd2 Adding OpPhi validation rules.
* Added tests
* Fixes SSA check for unreachable phi parents
* Fixes invalid cfg cleanup test
2018-03-27 17:26:26 -04:00
Andrey Tuganov
95843d7bd0 New spirv-1.3 rules for control barrier
Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/1427

Adjusting validation to the new rule:
"Before version 1.3, it is only valid to use this instruction with
TessellationControl, GLCompute, or Kernel execution models.
There is no such restriction starting with version 1.3."

Also fixed wrong version numbers in source/spirv_target_env.cpp.
2018-03-27 12:29:50 -04:00
Steven Perron
5e07ab1358 Handle more cases in copy propagate arrays.
When we change the type of an object that gets stored, we do not want to
change the type of the memory location being stored to.  In order to
still be able to do the rewrite, we will decompose and rebuild the
object so it is the type that can be stored.

Fixes #1416.
2018-03-27 11:04:49 -04:00