Commit Graph

453 Commits

Author SHA1 Message Date
Alan Baker
c3f34d8bf3 Fixes #1300. Adding checks for bad CCP transitions and unsettled values
* Now track propagation status and assert on bad statuses
 * Added helper methods to access instruction propagation status
* Modified the phi meet operator to properly reflect the paper it is
based on
* Modified SSA edge addition so that all edge are added, but only on
state changes
* Fixed a bug in instruction simulation where interesting conditional
branches would not mark the interesting edge as executed
 * Added a test to catch this bug
* Added an ostream operator for SSAPropagator::PropStatus
2018-02-18 19:41:34 -05:00
Arseny Kapoulkine
1054413600 Add constant folding rules for floating-point comparison
This change handles all 6 regular comparison types in two variations,
ordered (true if values are ordered *and* comparison is true) and
unordered (true if values are unordered *or* comparison is true).

Ordered comparison matches the default floating-point behavior on host
but we use std::isnan to check ordering explicitly anyway.

This change also slightly reworks the floating-point folding support
code to make it possible to define a folding operation that returns
boolean instead of floating point.

These tests exhaustively test ordered/unordered comparisons for
float/double.

Since for NaN inputs the comparison result doesn't depend on the
comparison function, we just test == and !=; NaN inputs result in true
unordered comparisons and false ordered comparisons.
2018-02-16 20:41:22 -05:00
Steven Perron
50f307f889 Simplify OpPhi instructions referencing unreachable continues
In dead branch elimination, we already recognize unreachable continue
blocks, and update OpPhi instruction accordingly.  This change adds an
extra check: if the head block has exactly 1 other incoming edge, then
replace the OpPhi with the value from that edge.

Fixes #1314.
2018-02-16 18:58:03 -05:00
Steven Perron
3756b387f3 Get CCP to use the constant floating point rules.
Fixes #1311
2018-02-16 13:49:47 -05:00
Arseny Kapoulkine
32a8e04c7d Add folding of redundant OpSelect insns
We can fold OpSelect into one of the operands in two cases:

- condition is constant
- both results are the same

Even if the original shader doesn't have either of these, if-conversion
pass sometimes ends up generating instructions like

   %7127 = OpSelect %int %3220 %7058 %7058

And this optimization cleans them up.
2018-02-15 10:03:22 -05:00
Steven Perron
6669d8163d Fold binary floating point operators.
Adds the floating rules for FAdd, FDiv, FMul, and FSub.

Contributes to #1164.
2018-02-14 15:48:15 -05:00
Stephen McGroarty
dd8400e150 Initial support for loop unrolling.
This patch adds initial support for loop unrolling in the form of a
series of utility classes which perform the unrolling. The pass can
be run with the command spirv-opt --loop-unroll. This will unroll
loops within the module which have the unroll hint set. The unroller
imposes a number of requirements on the loops it can unroll. These are
documented in the comments for the LoopUtils::CanPerformUnroll method in
loop_utils.h. Some of the restrictions will be lifted in future patches.
2018-02-14 15:44:38 -05:00
Alan Baker
229ebc0665 Fixes #1295. Mark undef values as varying in ccp.
* Undef now marked as varying in ccp
 * this prevents incorrect meet operations since phis were always not
 interesting
* added a test to catch the bug
2018-02-14 10:21:26 -05:00
Steven Perron
1d7b1423f9 Add folding of OpCompositeExtract and OpConstantComposite constant instructions.
Create files for constant folding rules.

Add the rules for OpConstantComposite and OpCompositeExtract.
2018-02-09 17:52:33 -05:00
Alexander Johnston
84ccd0b9ae Loop invariant code motion initial implementation 2018-02-08 22:55:47 -05:00
GregF
ca4457b4b6 SROA: Do replacement on structs with no partial references. 2018-02-08 15:20:02 -05:00
Steven Perron
06cdb96984 Make use of the instruction folder.
Implementation of the simplification pass.

- Create pass that calls the instruction folder on each instruction and
  propagate instructions that fold to a copy.  This will do copy
  propagation as well.

- Did not use the propagator engine because I want to modify the instruction
  as we go along.

- Change folding to not allocate new instructions, but make changes in
  place.  This change had a big impact on compile time.

- Add simplification pass to the legalization passes in place of
  insert-extract elimination.

- Added test cases for new folding rules.

- Added tests for the simplification pass

- Added a method to the CFG to apply a function to the basic blocks in
  reverse post order.

Contributes to #1164.
2018-02-07 23:01:47 -05:00
David Neto
e7fafdaa68 Fix test inclusion when Effcee is absent 2018-02-06 12:10:50 -05:00
Alan Baker
871022772e Registering a type now rebuilds it out of memory owned by the manager.
* Added TypeManager::RebuildType
 * rebuilds the type and its constituent types in terms of memory owned
 by the manager.
 * Used by TypeManager::RegisterType to properly allocate memory
* Adding an unit test to expose the issue
* Added some tests to provide coverage of RebuildType
* Added an accessor to the target pointer for a forward pointer
2018-02-06 10:17:56 -05:00
Steven Perron
bc1ec9418b Add general folding infrastructure.
Create the folding engine that will

1) attempt to fold an instruction.
2) iterates on the folding so small folding rules can be easily combined.
3) insert new instructions when needed.

I've added the minimum number of rules needed to test the features above.
2018-02-02 12:24:11 -05:00
Victor Lomuller
50e85c865c Add LoopUtils class to gather some loop transformation support.
This patch adds LoopUtils class to handle some loop related transformations. For now it has 2 transformations that simplifies other transformations such as loop unroll or unswitch:
 - Dedicate exit blocks: this ensure that all exit basic block
   (out-of-loop basic blocks that have a predecessor in the loop)
   have all their predecessors in the loop;
 - Loop Closed SSA (LCSSA): this ensure that all definitions in a loop are used inside the loop
   or in a phi instruction in an exit basic block.

It also adds the following capabilities:
 - Loop::IsLCSSA to test if the loop is in a LCSSA form
 - Loop::GetOrCreatePreHeaderBlock that can build a loop preheader if required;
 - New methods to allow on the fly updates of the loop descriptors.
 - New methods to allow on the fly updates of the CFG analysis.
 - Instruction::SetOperand to allow expression of the index relative to Instruction::NumOperands (to be compatible with the index returned by DefUseManager::ForEachUse)
2018-02-01 15:35:09 -05:00
Steven Perron
61d8c0384b Add pass to reaplce invalid opcodes
Creates a pass that will remove instructions that are invalid for the
current shader stage.  For the instruction to be considered for replacement

1) The opcode must be valid for a shader modules.
2) The opcode must be invalid for the current shader stage.
3) All entry points to the module must be for the same shader stage.
4) The function containing the instruction must be reachable from an entry point.

Fixes #1247.
2018-02-01 15:25:09 -05:00
Jeremy Hayes
cd68f2b176 Add adjacency validation pass
Validate OpPhi predecessors.
Validate OpLoopMerge successors.
Validate OpSelectionMerge successors.
Fix collateral damage to existing tests.
Remove ValidateIdWithMessage.OpSampledImageUsedInOpPhiBad.
2018-02-01 14:10:55 -05:00
Alan Baker
2735e0851e Remove constexpr from Analysis operators
* Had to remove templating from InstructionBuilder as a result
 * now preserved analyses are specified as a constructor argument
* updated tests and uses
* changed static_assert to a runtime assert
 * this should probably get further changes in the future
2018-01-31 14:44:43 -05:00
Alan Baker
16949236fe Prevent unnecessary changes to the IR in dead branch elim
* When handling unreachable merges and continues, do not optimize to the
same IR
 * pass did not check whether the unreachable blocks were in the
 optimized form before transforming them
* added a test to catch this issue
2018-01-30 16:51:58 -05:00
Alan Baker
e661da7941 Enhancements to block merging
* Should handle all possibilities
 * Stricter checks for what is disallowed:
  * header and header
  * merge and merge
 * Allow header and merge blocks to be merged
  * Erases the structured control declaration if merging header and
    merge blocks together.
2018-01-30 16:05:51 -05:00
Alan Baker
6704233d39 Fix dereference of possibly nullptr
* If the dead branch elim is performed on a module without structured
control flow, the OpSelectionMerge may not be present
 * Add a check for pointer validity before dereferencing
* Added a test to catch the bug
2018-01-30 10:15:43 -05:00
GregF
f28b106173 InsertExtractElim: Split out DeadInsertElim as separate pass 2018-01-30 08:52:14 -05:00
Alan Baker
1b46f7ecad Fixes in CCP for #1228
* Forces traversal of phis if the def has changed to varying
* Mark a phi as varying if all incoming values are varying
* added a test to catch the bug
2018-01-29 15:12:05 -05:00
Victor Lomuller
6018de81de Add LoopDescriptor as an IRContext analysis.
Move some function definitions from header to source to avoid circular definition.
2018-01-25 16:12:32 -05:00
Greg Fischer
684997eb72 DeadInsertElim: Detect and DCE dead Inserts
This adds Dead Insert Elimination to the end of the
--eliminate-insert-extract pass. See the new tests for examples of code
that will benefit.

Essentially, this removes OpCompositeInsert instructions which are not
used, either because there is no instruction which uses the value at the
index it is inserted, or because a subsequent insert intercepts any such
use.

This code has been seen to remove significant amounts of dead code from
real-life HLSL shaders being ported to Vulkan. In fact, it is needed to
remove dead texture samples which cause Vulkan validation layer errors
(unbound textures and samplers) if not removed . Such DCE is thus
required for fxc equivalence and legalization.

This analysis operates across "chains" of Inserts which can also contain
Phi instructions.
2018-01-25 16:07:21 -05:00
Alan Baker
2e93e806e4 Initial implementation of if conversion
* Handles simple cases only
* Identifies phis in blocks with two predecessors and attempts to
convert the phi to an select
 * does not perform code motion currently so the converted values must
 dominate the join point (e.g. can't be defined in the branches)
 * limited for now to two predecessors, but can be extended to handle
 more cases
* Adding if conversion to -O and -Os
2018-01-25 09:42:00 -08:00
Steven Perron
c4835e1bd8 Use id_map in Fold*ToConstant
The folding routines are suppose to use the id_map provided to map the
ids in the instruction.  The ones I just added are missing it.
2018-01-22 16:27:31 -05:00
Steven Perron
6c409e30a2 Add generic folding function and use in CCP
The current folding routines have a very cumbersome interface, make them
harder to use, and not a obvious how to extend.

This change is to create a new interface for the folding routines, and
show how it can be used by calling it from CCP.

This does not make a significant change to the behaviour of CCP.  In
general it should produce the same code as before; however it is
possible that an instruction that takes 32-bit integers as inputs and
the result is not a 32-bit integer or bool will not be folded as before.

It seems like andriod has a problem with INT32_MAX and the like.  I'll
explicitly define those if the are not already defined.
2018-01-22 14:26:49 -05:00
Alan Baker
3b780db7f8 Fixes infinite loop in ADCE
* Addresses how breaks are indentified to prevent infinite loops when
back to back loop share a merge and header
* Added test to catch the bug
2018-01-19 11:08:46 -05:00
Victor Lomuller
cf3b2a58c4 Introduce an instruction builder helper class.
The class factorize the instruction building process.
Def-use manager analysis can be updated on the fly to maintain coherency.
To be updated to take into account more analysis.
2018-01-19 10:17:45 -05:00
Alan Baker
73940aba1b Simplifying code for adding instructions to worklist
* AddToWorklist can now be called unconditionally
 * It will only add instructions that have not already been marked as
 live
 * Fixes a case where a merge was not added to the worklist because the
 branch was already marked as live
* Added two similar tests that fail without the fix
2018-01-18 20:36:46 -05:00
Steven Perron
34d4294c2c Create a pass to work around a driver bug related to OpUnreachable.
We have come across a driver bug where and OpUnreachable inside a loop
is causing the shader to go into an infinite loop.  This commit will try
to avoid this bug by turning OpUnreachable instructions that are
contained in a loop into branches to the loop merge block.

This is not added to "-O" and "-Os" because it should only be used if
the driver being targeted has this problem.

Fixes #1209.
2018-01-18 20:31:46 -05:00
Alan Baker
18618061cb Adding testcase for #1210 2018-01-18 12:58:07 -05:00
Alan Baker
80b743a570 Adding support for switch removal in ADCE
* Updated code to handle switches
* Enabled disabled test and added a couple new ones
2018-01-17 11:05:42 -05:00
Alan Baker
5ffe862f28 Fixes missing increment in common uniform elim
* Addresses #1203
* Increments inIdx in IsConstantIndexAccessChain
 * added test to catch the bug
2018-01-16 14:47:35 -05:00
Steven Perron
6cc772c3ce Skip SpecConstants in CCP.
At the moment specialization constants look like constants to ccp.  This
causes a problem because they are handled differently by the constant
manager.

I choose to simply skip over them, and not try to add them to the value
table.  We can do specialization before ccp if we want to be able to
propagate these values.

Fixes #1199.
2018-01-15 09:53:23 -05:00
Steven Perron
24f9947050 Move initialization of the const mgr to the constructor.
The current code expects the users of the constant manager to initialize
it with all of the constants in the module.  The problem is that you do
not want to redo the work multiple times.  So I decided to move that
code to the constructor of the constant manager.  This way it will
always be initialized on first use.

I also removed an assert that expects all constant instructions to be
successfully mapped.  This is because not all OpConstant* instruction
can map to a constant, and neither do the OpSpecConstant* instructions.

The real problem is that an OpConstantComposite can contain a member
that is OpUndef.  I tried to treat OpUndef like OpConstantNull, but this
failed because an OpSpecConstantComposite with an OpUndef cannot be
changed to an OpConstantComposite.  Since I feel this case will not be
common, I decided to not complicate the code.

Fixes #1193.
2018-01-12 13:53:21 -05:00
Alan Baker
672494da13 Adding ostream operators for IR structures
* Added for Instruction, BasicBlock, Function and Module
* Uses new disassembly functionality that can disassemble individual
instructions
 * For debug use only (no caching is done)
 * Each output converts module to binary, parses and outputs an
 individual instruction
* Added a test for whole module output
* Disabling Microsoft checked iterator warnings
* Updated check_copyright.py to accept 2018
2018-01-12 11:19:58 -05:00
Alan Baker
eb0c73dad6 Maintain instruction to block mapping in phi insertion
* Changed MemPass::InsertPhiInstructions to set basic blocks for new
phis
* Local SSA elim now maintains instr to block mapping
 * Added a test and confirmed it fails without the updated phis
* IRContext::set_instr_block no longer builds the map if the analysis is
invalid
* Added instruction to block mapping verification to
IRContext::IsConsistent()
2018-01-12 10:16:53 -05:00
Greg Fischer
5eafc00ad5 InsertExtractElim: Optimize through VectorShuffle, Mix
This improves Extract replacement to continue through VectorShuffle.
It will also handle Mix with 0.0 or 1.0 in the a-value of the desired
component.

To facilitate optimization of VectorShuffle, the algorithm was refactored
to pass around the indices of the extract in a vector rather than pass the
extract instruction itself. This allows the indices to be modified as the
algorithm progresses.
2018-01-12 09:41:45 -05:00
Alan Baker
3a054e1ddc Adding additional functionality to ADCE.
Modified ADCE to remove dead globals.
* Entry point and execution mode instructions are marked as alive
* Reachable functions and their parameters are marked as alive
* Instruction deletion now deferred until the end of the pass
* Eliminated dead insts set, added IsDead to calculate that value
instead
* Ported applicable dead variable elimination tests
* Ported dead constant elim tests

Added dead function elimination to ADCE
* ported dead function elim tests

Added handling of decoration groups in ADCE
* Uses a custom sorter to traverse decorations in a specific order
* Simplifies necessary checks

Updated -O and -Os pass lists.
2018-01-10 08:35:48 -05:00
Alan Baker
1b6cfd3409 Rewriting dead branch elimination.
Pass now paints live blocks and fixes constant branches and switches as
it goes. No longer requires structured control flow. It also removes
unreachable blocks as a side effect. It fixes the IR (phis) before doing
any code removal (other than terminator changes).

Added several unit tests for updated/new functionality.

Does not remove dead edge from a phi node:
* Checks that incoming edges are live in order to retain them
* Added BasicBlock::IsSuccessor
* added test

Fixing phi updates in the presence of extra backedge blocks

* Added tests to catch bug

Reworked how phis are updated

* Instead of creating a new Phi and RAUW'ing the old phi with it, I now
replace the phi operands, but maintain the def/use manager correctly.

For unreachable merge:

* When considering unreachable continue blocks the code now properly
checks whether the incoming edge will continue to be live.

Major refactoring for review

* Broke into 4 major functions
 * marking live blocks
 * marking structured targets
 * fixing phis
 * deleting blocks
2018-01-09 12:21:39 -05:00
Diego Novillo
e5560d64de Fix constant propagation of induction variables.
This fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/1143.
When an instruction transitions from constant to bottom (varying) in the
lattice, we were telling the propagator that the instruction was
varying, but never updating the actual value in the values table.

This led to incorrect value substitutions at the end of propagation.

The patch also re-enables CCP in -O and -Os.
2018-01-08 15:34:35 -05:00
Victor Lomuller
e8ad02f3dd Add loop descriptors and some required dominator tree extensions.
Add post-order tree iterator.

Add DominatorTreeNode extensions:
 - Add begin/end methods to do pre-order and post-order tree traversal from a given DominatorTreeNode

Add DominatorTree extensions:
  - Add begin/end methods to do pre-order and post-order tree traversal
  - Tree traversal ignore by default the pseudo entry block
  - Retrieve a DominatorTreeNode from a basic block

Add loop descriptor:
  - Add a LoopDescriptor class to register all loops in a given function.
  - Add a Loop class to describe a loop:
    - Loop parent
    - Nested loops
    - Loop depth
    - Loop header, merge, continue and preheader
    - Basic blocks that belong to the loop

Correct a bug that forced dominator tree to be constantly rebuilt.
2018-01-08 09:31:13 -05:00
Steven Perron
ccb921dd2b Allow getting the base pointer of an image load/store.
In value numbering, we treat loads and stores of images, ie OpImageLoad,
as a memory operation where it is interested in the "base address" of
the instruction.  In those cases, it is an image instruction.

The problem is that `Instruction::GetBaseAddress()` does not account for
the image instructions, so the assert at the end to make sure it found
a valid base address for its addressing mode fails.

The solution is to look at the load/store instruction to determine how
the assertion should be done.

Fixes #1160.
2018-01-05 13:26:10 -05:00
Diego Novillo
716718a5e9 Fix infinite simulation cycles in SSA propagator.
This fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/1159.  I
had missed a nuance in the original algorithm.  When simulating Phi
instructions, the SSA edges out of a Phi instruction should never be
added to the list of edges to simulate.

Phi instructions can be in SSA def-use cycles with other Phi
instructions.  This was causing the propagator to fall into an infinite
loop when the same def-use edge kept being added to the queue.

The original algorithm in the paper specifically separates the visit of
a Phi instruction vs the visit of a regular instruction.  This fix makes
the implementation match the original algorithm.
2018-01-05 10:29:39 -05:00
Pierre Moreau
702852bd22 Opt: Make DecorationManager::HaveTheSameDecorations symmetric
Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/1112

Also: Add SpvOpDecorateId to IsAnnotationInst()
2018-01-04 14:07:25 -05:00
Diego Novillo
5f100789fb Handle execution termination instructions when building edges.
This fixes issue https://github.com/KhronosGroup/SPIRV-Tools/issues/1153.

When building CFG edges, edges out of a OpKill and OpUnreachable
instruction should be directed to the CFG's pseudo exit block.
2018-01-03 15:25:03 -05:00
Diego Novillo
135150a1a8 Do not insert Phi nodes in CCP propagator.
In CCP we should not need to insert Phi nodes because CCP never looks at
loads/stores.  This required adjusting two tests that relied on Phi
instructions being inserted.  I changed the tests to have the Phi
instructions pre-inserted.

I also added a new test to make sure that CCP does not try to look
through stores and loads.

Finally, given that CCP does not handle loads/stores, it's better to run
mem2reg before it.  I've changed the -O/-Os schedules to run local
multi-store elimination before CCP.

Although this is just an efficiency fix for CCP, it is
also working around a bug in Phi insertion.  When Phi instructions are
inserted, they are never associated a basic block.  This causes a
segfault when the propagator tries to lookup CFG edges when analyzing
Phi instructions.
2018-01-03 15:12:25 -05:00
GregF
226f263cbc Test: Fix linux/gcc defined-but-not-used warnings/errors 2017-12-29 09:22:36 -05:00
Diego Novillo
4ba9dcc8a0 Implement SSA CCP (SSA Conditional Constant Propagation).
This implements the conditional constant propagation pass proposed in

Constant propagation with conditional branches,
Wegman and Zadeck, ACM TOPLAS 13(2):181-210.

The main logic resides in CCPPass::VisitInstruction.  Instruction that
may produce a constant value are evaluated with the constant folder. If
they produce a new constant, the instruction is considered interesting.
Otherwise, it's considered varying (for unfoldable instructions) or
just not interesting (when not enough operands have a constant value).

The other main piece of logic is in CCPPass::VisitBranch.  This
evaluates the selector of the branch.  When it's found to be a known
value, it computes the destination basic block and sets it.  This tells
the propagator which branches to follow.

The patch required extensions to the constant manager as well. Instead
of hashing the Constant pointers, this patch changes the constant pool
to hash the contents of the Constant.  This allows the lookups to be
done using the actual values of the Constant, preventing duplicate
definitions.
2017-12-21 14:29:45 -05:00
Steven Perron
756b277fb8 Store all enabled capabilities in the feature manger.
In order to keep track of all of the implicit capabilities as well as
the explicit ones, we will add them all to the feature manager.  That is
the object that needs to be queried when checking if a capability is
enabled.

The name of the "HasCapability" function in the module was changed to
make it more obvious that it does not check for implied capabilities.

Keep an spv_context and AssemblyGrammar in IRContext
2017-12-21 11:14:53 -05:00
Alan Baker
1ab8ad654a Fixing bugs in type manager memory management
* changed the way duplicate types are removed to stop copying
instructions
* Reworked RemoveDuplicatesPass::AreTypesSame to use type manager and
type equality
* Reworked TypeManager memory management to store a pool of unique
pointers of types
 * removed unique pointers from id map
 * fixed instances where free'd memory could be accessed
2017-12-21 08:59:06 -05:00
Pierre Moreau
424f744db1 Opt: Fix implementation and comment of AreDecorationsTheSame
Target should not be ignored when comparing decorations in RemoveDuplicates
Opt: Remove unused code in RemoveDuplicateDecorations
2017-12-19 15:36:47 -05:00
Steven Perron
79a00649b4 Allow pointers to pointers in logical addressing mode.
A few optimizations are updates to handle code that is suppose to be
using the logical addressing mode, but still has variables that contain
pointers as long as the pointer are to opaque objects.  This is called
"relaxed logical addressing".

|Instruction::GetBaseAddress| will check that pointers that are use meet
the relaxed logical addressing rules.  Optimization that now handle
relaxed logical addressing instead of logical addressing are:

 - aggressive dead-code elimination
 - local access chain convert
 - local store elimination passes.
2017-12-19 14:29:14 -05:00
Steven Perron
b86eb6842b Convert private variables to function scope.
When a private variable is used in a single function, it can be
converted to a function scope variable in that function.  This adds a
pass that does that.  The pass can be enabled using the option
`--private-to-local`.

This transformation allows other transformations to act on these
variables.

Also moved `FindPointerToType` from the inline class to the type manager.
2017-12-19 14:21:04 -05:00
Alan Baker
616908503d Improving the usability of the type manager. The type manager hashes
types. This allows the lookup of type declaration ids from arbitrarily
constructed types. Users should be cautious when dealing with non-unique
types (structs and potentially pointers) to get the exact id if
necessary.

* Changed the spec composite constant folder to handle ambiguous composites
* Added functionality to create necessary instructions for a type
* Added ability to remove ids from the type manager
2017-12-18 08:20:56 -05:00
GregF
0f80406315 ADCE: Only mark true breaks and continues of live loops
This fixes issue #1075

- Mark continue when conditional branch with merge block.
  Only mark if merge block is not continue block.

- Handle conditional branch break with preceding merge
2017-12-15 11:53:57 -05:00
Greg Fischer
22faa2b083 ADCE: Empty Loop Elimination
This entirely eliminates loops which do not contain live code.
2017-12-12 13:53:15 -05:00
Steven Perron
07ce16d1e7 Set the parent for basic blocks during inlining.
Inlining is not setting the parent (function) for each basic block.
This can cause problems for later optimizations.  The solution is to set
the parent for each new block just before it is linked into the
function.
2017-12-12 13:39:08 -05:00
Alan Baker
867451f49e Add scalar replacement
Adds a scalar replacement pass. The pass considers all function scope
variables of composite type. If there are accesses to individual
elements (and it is legal) the pass replaces the variable with a
variable for each composite element and updates all the uses.

Added the pass to -O
Added NumUses and NumUsers to DefUseManager
Added some helper methods for the inst to block mapping in context
Added some helper methods for specific constant types

No longer generate duplicate pointer types.

* Now searches for an existing pointer of the appropriate type instead
of failing validation
* Fixed spec constant extracts
* Addressed changes for review
* Changed RunSinglePassAndMatch to be able to run validation
 * current users do not enable it

Added handling of acceptable decorations.

* Decorations are also transfered where appropriate

Refactored extension checking into FeatureManager

* Context now owns a feature manager
 * consciously NOT an analysis
 * added some test
* fixed some minor issues related to decorates
* added some decorate related tests for scalar replacement
2017-12-11 10:51:13 -05:00
GregF
78c025abe9 MultiStore: Support OpVariable Initialization
Treat an OpVariable with initialization as if it was an OpStore.
With PR #1073, this completes work for issue #1017.
2017-12-11 10:37:14 -05:00
GregF
c6fdf68c2f SingleStore: Support OpVariable Initialization
Treat an OpVariable with initialization as if it was an OpStore.
This fixes issue #1017.
2017-12-08 16:02:14 -05:00
Steven Perron
5d602abd66 Add global redundancy elimination
Adds a pass that looks for redundant instruction in a function, and
removes them.  The algorithm is a hash table based value numbering
algorithm that traverses the dominator tree.

This pass removes completely redundant instructions, not partially
redundant ones.
2017-12-07 18:35:38 -05:00
Steven Perron
851e1ad985 Kill names and decoration in inlining.
Currently when inlining a call, the name and decorations for the result of the
call is not deleted.  This should be changed.  Added a test for this as well.

This fixes issue #622.
2017-12-07 12:20:45 -05:00
Victor Lomuller
731d1899b1 Add depth first iterator for trees
- Add generic depth first iterator
 - Update the dominator tree to use this iterator instead of "randomly"
   iterate over the nodes
2017-12-07 10:07:56 -05:00
Stephen McGroarty
8ba68fa9b9 Dominator Tree Analysis (#3)
Support for dominator and post dominator analysis on ir::Functions. This patch contains a DominatorTree class for building the tree and DominatorAnalysis and DominatorAnalysisPass classes for interfacing and caching the built trees.
2017-12-05 22:59:43 -05:00
Diego Novillo
e9ecc0cbfd Remove cfg_ field from SSAPropagator class - NFC.
When I moved the CFG into IRContext
(https://github.com/KhronosGroup/SPIRV-Tools/pull/1019), I forgot to
update SSAPropagator to stop requiring one.

Fixed with this patch.
2017-12-04 15:28:21 -05:00
Steven Perron
65046eca7c Change IRContext::KillInst to delete instructions.
The current method of removing an instruction is to call ToNop.  The
problem with this is that it leaves around an instruction that later
passes will look at.  We should just delete the instruction.

In MemPass there is a utility routine called DCEInst.  It can delete
essentially any instruction, which can invalidate pointers now that they
are actually deleted.  The interface was changed to add a call back that
can be used to update any local data structures that contain
ir::Intruction*.
2017-12-04 11:07:45 -05:00
Steven Perron
b35b52f97b Compute value number when the value table is constructed.
Computing the value numbers on demand, as we do now, can lead to
different results depending on the order in which the users asks for
the value numbers.  To make things more stable, we compute them ahead
of time.
2017-12-04 11:02:04 -05:00
GregF
8dd3d93cf6 AggressiveDCE: Add merge and continue branches for live loop.
This ensures that an if-break is not eliminated from a loop.

This fixes issue #989
2017-11-29 09:56:21 -05:00
Diego Novillo
8ffed974ac Fix windows build. unsigned vs signed comparison in EXPECT_EQ. 2017-11-28 09:13:42 -05:00
Diego Novillo
74327845aa Generic value propagation engine.
This class implements a generic value propagation algorithm based on the
conditional constant propagation algorithm proposed in

     Constant propagation with conditional branches,
     Wegman and Zadeck, ACM TOPLAS 13(2):181-210.

The implementation is based on

     A Propagation Engine for GCC
     Diego Novillo, GCC Summit 2005
     http://ols.fedoraproject.org/GCC/Reprints-2005/novillo-Reprint.pdf

The purpose of this implementation is to act as a common framework for any
transformation that needs to propagate values from statements producing new
values to statements using those values.
2017-11-27 23:32:06 -05:00
Diego Novillo
83228137e1 Re-format source tree - NFC.
Re-formatted the source tree with the command:

$ /usr/bin/clang-format -style=file -i \
    $(find include source tools test utils -name '*.cpp' -or -name '*.h')

This required a fix to source/val/decoration.h.  It was not including
spirv.h, which broke builds when the #include headers were re-ordered by
clang-format.
2017-11-27 14:31:49 -05:00
Alan Baker
746bfd210a Adding new def -> use mapping container
Replaced representation of uses

* Changed uses from unordered_map<uint32_t, UseList> to
set<pairInstruction*, Instruction*>>
* Replaced GetUses with ForEachUser and ForEachUse functions
* updated passes to use new functions
* partially updated tests
* lots of cleanup still todo

Adding an unique id to Instruction generated by IRContext

Each instruction is given an unique id that can be used for ordering
purposes. The ids are generated via the IRContext.

Major changes:
* Instructions now contain a uint32_t for unique id and a cached context
pointer
 * Most constructors have been modified to take a context as input
 * unfortunately I cannot remove the default and copy constructors, but
 developers should avoid these
* Added accessors to parents of basic block and function
* Removed the copy constructors for BasicBlock and Function and replaced
them with Clone functions
* Reworked BuildModule to return an IRContext owning the built module
 * Since all instructions require a context, the context now becomes the
basic unit for IR
* Added a constructor to context to create an owned module internally
* Replaced uses of Instruction's copy constructor with Clone whereever I
found them
* Reworked the linker functionality to perform clones into a different
context instead of moves
* Updated many tests to be consistent with the above changes
 * Still need to add new tests to cover added functionality
* Added comparison operators to Instruction

Adding tests for Instruction, IRContext and IR loading

Fixed some header comments for BuildModule

Fixes to get tests passing again

* Reordered two linker steps to avoid use/def problems
* Fixed def/use manager uses in merge return pass
* Added early return for GetAnnotations
* Changed uses of Instruction::ToNop in passes to IRContext::KillInst

Simplifying the uses for some contexts in passes
2017-11-23 16:40:02 -05:00
Lei Zhang
b02c9a5802 Allow derived access chain without uses in access chain conversion 2017-11-23 16:00:28 -05:00
Steven Perron
28c415500d Create a local value numbering pass
Creates a pass that removes redundant instructions within the same basic
block.  This will be implemented using a hash based value numbering
algorithm.

Added a number of functions that check for the Vulkan descriptor types.
These are used to determine if we are variables are read-only or not.

Implemented a function to check if loads and variables are read-only.
Implemented kernel specific and shader specific versions.

A big change is that the Combinator analysis in ADCE is factored out
into the IRContext as an analysis. This was done because it is being
reused in the value number table.
2017-11-23 11:45:09 -05:00
GregF
e28edd458b Optimize loads/stores on nested structs
Also fix LocalAccessChainConvert test: nested structs now convert

Add InsertExtractElim test for nested struct
2017-11-21 17:56:03 -05:00
Alan Baker
a771713e42 Adding an unique id to Instruction generated by IRContext
Each instruction is given an unique id that can be used for ordering
purposes. The ids are generated via the IRContext.

Major changes:
* Instructions now contain a uint32_t for unique id and a cached context
pointer
 * Most constructors have been modified to take a context as input
 * unfortunately I cannot remove the default and copy constructors, but
 developers should avoid these
* Added accessors to parents of basic block and function
* Removed the copy constructors for BasicBlock and Function and replaced
them with Clone functions
* Reworked BuildModule to return an IRContext owning the built module
 * Since all instructions require a context, the context now becomes the
basic unit for IR
* Added a constructor to context to create an owned module internally
* Replaced uses of Instruction's copy constructor with Clone whereever I
found them
* Reworked the linker functionality to perform clones into a different
context instead of moves
* Updated many tests to be consistent with the above changes
 * Still need to add new tests to cover added functionality
* Added comparison operators to Instruction
* Added an internal option to LinkerOptions to verify merged ids are
unique
* Added a test for the linker to verify merged ids are unique

* Updated MergeReturnPass to supply a context
* Updated DecorationManager to supply a context for cloned decorations

* Reworked several portions of the def use tests in anticipation of next
set of changes
2017-11-20 17:49:10 -05:00
Lei Zhang
4019bcfd57 Fix hard-coded header path
If SPIRV-Tools is used as an external project and have
googletest being kept in the same directory as it, we
won't have gmock-matchers.h in external/. This will
result in a compilation error.

Use gmock.h instead.
2017-11-17 19:54:55 -05:00
Steven Perron
eb4653a67f Add the decoration manager to the IRContext.
To make the decoration manger available everywhere, and to reduce the
number of times it needs to be build, I add one the IRContext.

As the same time, I move code that modifies decoration instruction into
the IRContext from mempass and the decoration manager.  This will make
it easier to keep everything up to date.

This should take care of issue #928.
2017-11-15 12:48:03 -05:00
Alan Baker
a92d69b43d Initial implementation of merge return pass.
Works with current DefUseManager infrastructure.

Added merge return to the standard opts.

Added validation to passes.

Disabled pass for shader capabilty.
2017-11-15 10:27:04 -05:00
Diego Novillo
98281ed411 Add analysis to compute mappings between instructions and basic blocks.
This analysis builds a map from instructions to the basic block that
contains them.  It is accessed via get_instr_block().  Once built, it is kept
up-to-date by the IRContext, as long as instructions are removed via
KillInst.

I have not yet marked passes that preserve this analysis. I will do it
in a separate change.

Other changes:

- Add documentation about analysis values requirement to be powers of 2.
- Force a re-build of the def-use manager in tests.
- Fix AllPreserveFirstOnlyAfterPassWithChange to use the
  DummyPassPreservesFirst pass.
- Fix sentinel value for IRContext::Analysis enum.

- Fix logic for checking if the instr<->block mapping is valid in KillInst.
2017-11-13 13:21:48 -05:00
Daniel Schürmann
a76d0977ac Fix decorations of inlined functions.
Fixes issue #728.  Currently the inliner is not generating decorations for
inlined code which corresponds to function code which has decorations. An
example of decorations that are relevant: RelaxedPrecision, NoContraction.

The solution is to replicate the decoration during inlining.
2017-11-13 12:49:25 -05:00
David Neto
76555bd4ba Tests: Add optional dependency on Effcee stateful matcher
Add Effcee as an optional dependency for use in tests.  In future it will
be a required dependency.

Effcee is a stateful pattern matcher that has much of the functionality
of LLVM's FileCheck, except in library form.  Effcee makes it much easier
to write tests for optimization passes.

Demonstrate its use in a test for the strength-reduction pass.

Update README.md with example commands of how to get sources.

Update Appveyor and Travis-CI build rules.

Also: Include test libraries if not SPIRV_SKIP_TESTS
- SPIRV_SKIP_TESTS is implied by SPIRV_SKIP_EXECUTABLES
2017-11-13 11:34:21 -05:00
Steven Perron
f32d11f74b Add the IRContext (part 2): Add def-use manager
This change will move the instances of the def-use manager to the
IRContext.  This allows it to persists across optimization, and does
not have to be rebuilt multiple times.

Added test to ensure that the IRContext is validating and invalidating
the analyses correctly.
2017-11-08 13:35:34 -05:00
GregF
ac04b2faea Opt: Fix HasLoads to not report decoration as load. 2017-11-07 17:39:58 -05:00
Steven Perron
476cae6f7d Add the IRContext (part 1)
This is the first part of adding the IRContext.  This class is meant to
hold the extra data that is build on top of the module that it
owns.

The first part will simply create the IRContext class and get it passed
to the passes in place of the module.  For now it does not have any
functionality of its own, but it acts more as a wrapper for the module.

The functions that I added to the IRContext are those that either
traverse the headers or add to them.  I did this because we may decide
to have other ways of dealing with these sections (for example adding a
type pool, or use the decoration manager).

I also added the function that add to the header because the IRContext
needs to know when an instruction is added to update other data
structures appropriately.

Note that there is still lots of work that needs to be done.  There are
still many places that change the module, and do not inform the context.
That will be the next step.
2017-10-31 13:46:05 -04:00
GregF
94bec26afe ADCE: Dead if elimination
Mark structured conditional branches live only if one or more instructions
in their associated construct is marked live. After closure, replace dead
structured conditional branches with a branch to its merge and remove
dead blocks.

ADCE: Dead If Elim: Remove duplicate StructuredOrder code

Also generalize ComputeStructuredOrder so that the caller can specify the
root block for the order. Phi insertion uses pseudo_entry_block and adce and
dead branch elim use the first block of the function.

ADCE: Dead If Elim: Pull redundant code out of InsertPhiInstructions

ADCE: Dead If Elim: Encapsulate CFG Cleanup Initialization

ADCE: Dead If Elim: Remove redundant code from ADCE initialization

ADCE: Dead If: Use CFGCleanup to eliminate newly dead blocks

Moved bulk of CFG Cleanup code into MemPass.
2017-10-31 11:51:30 -04:00
Steven Perron
94dc66b74d Change the sections in the module to use the InstructionList class.
This change will replace a number of the
std::vector<std::unique_ptr<Instruction>> member of the module to
InstructionList.  This is for consistency and to make it easier to
delete instructions that are no longer needed.
2017-10-25 15:52:06 -04:00
Daniel Schürmann
97990dc907 Fixed --eliminate-common-uniform so that it does not eliminate loads of volatile variables. 2017-10-24 11:17:33 -04:00
Steven Perron
5834719fc1 Add pass to remove dead variables at the module level.
There does not seem to be any pass that remove global variables.  I
think we could use one.  This pass will look specifically for global
variables that are not referenced and are not exported.  Any decoration
associated with the variable will also be removed.  However, this could
cause types or constants to become unreferenced.  They will not be
removed.  Another pass will have to be called to remove those.
2017-10-23 13:57:05 -04:00
David Neto
2436794736 Optimizer: OpModuleProcessed is in its own layout section
This is a recent decision from the SPIR WG.  The spec update
has not yet been published.
Khronos SPIR-V internal issue 199
2017-10-23 10:46:37 -04:00
Steven Perron
bb7802b18c Change BasicBlock to use InstructionList to hold instructions.
This is the first step in replacing the std::vector of Instruction
pointers to using and intrusive linked list.

To this end, we created the InstructionList class.  It inherites from
the IntrusiveList class, but add the extra concept of ownership.  An
InstructionList owns the instruction that are in it.  This is to be
consistent with the current ownership rules where the vector owns the
instruction that are in it.

The other larger change is that the inst_ member of the BasicBlock class
was changed to using the InstructionList class.

Added test for the InsertBefore functions, and making sure that the
InstructionList destructor will delete the elements that it contains.

I've also add extra comments to explain ownership a little better.
2017-10-20 12:37:44 -04:00
David Neto
8ec62deb23 The reviewed cfg_cleanup optimize pass 2017-10-19 15:28:09 -04:00
Diego Novillo
c75704ec08 CFG cleanup pass - Remove unreachable blocks.
- Adds a new pass CFGCleanupPass.  This serves as an umbrella pass to
  remove unnecessary cruft from a CFG.
- Currently, the only cleanup operation done is the removal of
  unreachable basic blocks.
- Adds unit tests.
- Adds a flag to spirvopt to execute the pass (--cfg-cleanup).
2017-10-19 15:16:29 -04:00
GregF
1a9061a2be ADCE: Treat privates like locals in entry point with no calls
This is needed for ongoing legalization of HLSL. It allows removal
of accesses to textures/buffers that are not used.
2017-10-13 15:39:14 -04:00
GregF
63064bd9eb DeadBranchElim: Add dead case elimination
Expands dead branch elimination to eliminate dead switch cases. It also
changes dbe to eliminate orphaned merge blocks and recursively eliminate
any blocks thereby orphaned.
2017-10-12 11:44:05 -04:00
Pierre Moreau
86627f7b3f Implement Linker (module combiner)
Add extra iterators for ir::Module's sections
Add extra getters to ir::Function
Add a const version of BasicBlock::GetLabelInst()

Use the max of all inputs' version as version

Split debug in debug1 and debug2
- Debug1 instructions have to be placed before debug2 instructions.

Error out if different addressing or memory models are found

Exit early if no binaries were given

Error out if entry points are redeclared

Implement copy ctors for Function and BasicBlock
- Visual Studio ends up generating copy constructors that call deleted
  functions while compiling the linker code, while GCC and clang do not.
  So explicitly write those functions to avoid Visual Studio messing up.

Move removing duplicate capabilities to its own pass

Add functions running on all IDs present in an instruction

Remove duplicate SpvOpExtInstImport

Give default options value for link functions

Remove linkage capability if not making a library

Check types before allowing to link

Detect if two types/variables/functions have different decorations

Remove decorations of imported variables/functions and their types

Add a DecorationManager

Add a method for removing all decorations of id

Add methods for removing operands from instructions

Error out if one of the modules has a non-zero schema

Update README.md to talk about the linker

Do not freak out if an imported built-in variable has no export
2017-10-06 18:33:53 -04:00
GregF
da04f5640e AggressiveDCE: Fix to not treat parameter memory refs as local
This fixes a bug that incorrectly deletes stores to parameters, which
can be used to return values from functions.
2017-10-05 10:59:45 -04:00
Pierre Moreau
c87e9671ab Compact-ids pass should update the header ID bound 2017-10-03 11:24:28 -04:00
David Neto
77feb8dd03 Compact-ids pass should update instruction's result_id member
Also update the result type field.

Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/827
2017-09-27 08:31:05 -04:00
Steven Perron
e43c91046b Create the dead function elimination pass
Creates a pass called eliminate dead functions that looks for functions
that could never be called, and deletes them from the module.

To support this change a new function was added to the Pass class to
traverse the call trees from diffent starting points.

Includes a test to ensure that annotations are removed when deleting a
dead function.  They were not, so fixed that up as well.

Did some cleanup of the assembly for the test in pass_test.cpp.  Trying
to make them smaller and easier to read.
2017-09-26 11:18:06 -04:00
David Neto
33b879c105 elim-multi-store: only patch loop header phis that we created
There can already be OpPhi instructions in a loop header that
are unrelated to the optimization.  We should not be patching those.

Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/826
2017-09-21 10:01:30 -04:00
Steven Perron
e4c7d8e748 Add strength reduction; for now replace multiply by power of 2
Create a new optimization pass, strength reduction, which will replace
integer multiplication by a constant power of 2 with an equivalent bit
shift.  More changes could be added later.

- Does not duplicate constants

- Adds vector |Concat| utility function to a common test header.
2017-09-18 17:01:36 -04:00
David Neto
25ddfec08e Inliner: Fix LoopMerge when inline into loop header of multi block loop
This adapts the fix for the single-block loop.  Split the loop like
before.  But when we move the OpLoopMerge back to the loop header,
redirect the continue target only when the original loop was a single
block loop.

Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/800
2017-09-05 19:46:24 -04:00
David Neto
860c4197b0 Inliner: Remap callee entry block id to single-trip loop header
Otherwise cloned phis can be invalid.

Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/790
2017-09-01 15:56:14 -04:00
David Neto
efff5fabfa Inline: Fix single-block loop caller cases
If the caller block is a single-block loop and inlining will
replace the caller block by several blocks, then:
- The original OpLoopMerge instruction will end up in the *last*
  such block.  That's the wrong place to put it.
- Move it back to the end of the first block.
- Update its Continue Target ID to point to the last block

We also have to take care of cases where the inlined code
begins with a structured header block.  In this case
we need to ensure the restored OpLoopMerge does not appear
in the same block as the merge instruction from the callee's
first block.

Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/787
2017-09-01 15:47:17 -04:00
GregF
7c3de19ce7 DeadBranchElim: Fix dead block detection to ignore backedges
- DeadBranchElim: Make sure to mark orphan'd merge blocks and continue
targets as live.
- Add test with loop in dead branch
- Add test that orphan'd merge block is handled.

Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/776
2017-08-30 13:37:46 -04:00
GregF
a699d1ade7 Inline: Fix remapping of non-label forward references in callee phi 2017-08-29 18:35:05 -06:00
GregF
429ca05b3f Opt: Create InlineOpaquePass
Only inline calls to functions with opaque params or return

TODO: Handle parameter type or return type where the opqaue
type is buried within an array.
2017-08-18 18:04:30 -04:00
GregF
c8c86a0d36 Opt: Have "size" passes process full entry point call tree.
Includes code to deal correctly with OpFunctionParameter. This
is needed by opaque propagation which may not exhaustively inline
entry point functions.

Adds ProcessEntryPointCallTree: a method to do work on the
functions in the entry point call trees in a deterministic order.
2017-08-18 10:16:01 -04:00
GregF
1d477b9898 Opt: Add opaque tests 2017-08-15 15:54:41 -06:00
GregF
b0310a4156 ADCE: Add support for function calls
ADCE will now generate correct code in the presence of function calls.
This is needed for opaque type optimization needed by glslang. Currently
all function calls are marked as live. TODO: mark calls live only if they
write a non-local.
2017-08-10 17:30:05 -04:00
David Neto
2a1014be9c Inliner: callee can have early return that isn't multi-return
Avoid generating an invalid OpLabel.
Create the continue target for the single-trip loop only if
you actually created the header for the single-trip loop.

Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/755
2017-08-10 11:43:44 -04:00
GregF
e28bd39997 Inline: Split out InlineExhaustivePass from InlinePass 2017-08-04 17:56:46 -04:00
GregF
f4b29f3bf7 Add CommonUniformElim pass
- UniformElim: Only process reachable blocks

- UniformElim: Don't reuse loads of samplers and images across blocks.
  Added a second phase which only reuses loads within a block for samplers
  and images.

- UniformElim: Upgrade CopyObject skipping in GetPtr

- UniformElim: Add extensions whitelist
  Currently disallowing SPV_KHR_variable_pointers because it doesn't
  handle extended pointer forms.

- UniformElim: Do not process shaders with GroupDecorate

- UniformElim: Bail on shaders with non-32-bit ints.

- UniformElim: Document support for only single index and add TODO.
2017-08-03 11:34:58 -04:00
GregF
c1b46eedbd Add MemPass, move all shared functions to it. 2017-08-02 14:24:02 -04:00
GregF
7954740d54 Opt: Delete names and decorations of dead instructions 2017-07-26 18:36:41 -04:00
Lei Zhang
9f6efc76c8 Opt: HasOnlySupportedRefs should consider OpCopyObject
This fixes test failure after merging the previous pull request.
2017-07-25 23:22:09 -04:00
GregF
1182415581 Add extension whitelists to size-reduction passes.
Currently only SPV_KHR_variable_pointers is disallowed in passes which
do pointer analysis. Positive and negative tests of the general extensions
mechanism were added to aggressive_dce but cover all passes.
2017-07-25 19:14:02 -04:00
GregF
adb237f3bd Fix handling of CopyObject in GetPtr and its call sites 2017-07-21 18:08:01 -04:00
GregF
9de4e69856 Add AggressiveDCEPass
Create aggressive dead code elimination pass
This pass eliminates unused code from functions. In addition,
it detects and eliminates code which may have spurious uses but which do
not contribute to the output of the function. The most common cause of
such code sequences is summations in loops whose result is no longer used
due to dead code elimination. This optimization has additional compile
time cost over standard dead code elimination.

This pass only processes entry point functions. It also only processes
shaders with logical addressing. It currently will not process functions
with function calls. It currently only supports the GLSL.std.450 extended
instruction set. It currently does not support any extensions.

This pass will be made more effective by first running passes that remove
dead control flow and inlines function calls.

This pass can be especially useful after running Local Access Chain
Conversion, which tends to cause cycles of dead code to be left after
Store/Load elimination passes are completed. These cycles cannot be
eliminated with standard dead code elimination.

Additionally: This transform uses a whitelist of instructions that it
knows do have side effects, (a.k.a. combinators).  It assumes other
instructions have side effects: it will not remove them, and assumes
they have side effects via their ID operands.
2017-07-10 11:30:25 -04:00
GregF
cc8bad3a5b Add LocalMultiStoreElim pass
A SSA local variable load/store elimination pass.
For every entry point function, eliminate all loads and stores of function
scope variables only referenced with non-access-chain loads and stores.
Eliminate the variables as well.

The presence of access chain references and function calls can inhibit
the above optimization.

Only shader modules with logical addressing are currently processed.
Currently modules with any extensions enabled are not processed. This
is left for future work.

This pass is most effective if preceeded by Inlining and
LocalAccessChainConvert. LocalSingleStoreElim and LocalSingleBlockElim
will reduce the work that this pass has to do.
2017-07-07 17:54:21 -04:00
GregF
52e247f221 DeadBranchElim: Add DeadBranchElimPass 2017-07-07 15:16:25 -04:00
David Neto
35a0695844 Include memory and semantics IDs when iterating over inbound IDs
Fixes Instruction::ForEachInId so it covers
SPV_OPERAND_TYPE_MEMORY_SEMANTICS_ID and SPV_OPERAND_TYPE_SCOPE_ID.
Future proof a bit by using the common spvIsIdType routine.

Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/697
2017-07-05 10:36:57 -04:00
GregF
ad1d0351a0 BlockMerge: Add BlockMergePass
Also, add BasicBlock::tail()
2017-06-27 11:31:33 -04:00
GregF
6136bf9e0b mem2reg: Add InsertExtractElimPass 2017-06-21 08:13:15 -04:00
GregF
0c5722fc01 mem2reg: Add LocalSingleStoreElimPass
Eliminate function scope variables with one store, if possible.
2017-06-19 10:43:02 -04:00
GregF
7c8da66bc2 mem2reg: Add pass to eliminate local loads and stores in single block. 2017-06-12 17:03:47 -04:00
GregF
aa7e687ef0 Mem2Reg: Add Local Access Chain Convert pass
- Supports OpAccessChain and OpInBoundsAccessChain
- Does not process modules with non-32-bit integer types.
2017-06-04 12:49:27 -04:00
Greg Fischer
bba812f4e4 Inline: Inline early return function if no returns in loop. 2017-05-12 17:18:00 -04:00
Mike Lothain
3f90058d2f Update set_spec_const_default_value_test.cpp
Work around warning of dangling else
2017-05-08 10:41:48 -04:00
GregF
a107d349e3 Inline: Do not inline functions with multiple returns (for now) 2017-04-25 16:50:57 -06:00
qining
144f59e451 Add bit pattern interface for setting default value for spec constants 2017-04-21 11:22:47 -04:00
Andrey Tuganov
1e309af80a Added --compact-ids to /tools/opt
The pass remaps ids to a compact set which starts with %1 and
has no gaps.
2017-04-20 10:54:39 -04:00
David Neto
11a867f412 Add FlattenDecoration transform
Add --flatten-decorations to spirv-opt

Flattens decoration groups.  That is, replace OpDecorationGroup
and its uses in OpGroupDecorate and OpGroupMemberDecorate with
ordinary OpDecorate and OpMemberDecorate instructions.

Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/602
2017-04-06 11:19:56 -04:00
David Neto
afc60bbebf Fix optimizer on when to write the binary
The spvtools::Optimizer::Run method should also write the output binary
if optimization succeeds without changes but the output binary vector
does not have exactly the same contents as the input binary.
We have to check both the base pointer of the storage and the size of
the vector

Added a test for this too.

Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/611
2017-04-03 15:48:50 -04:00
David Neto
ceb1d4f2fd Avoid inlining calls to external functions
External functions don't have bodies to inline anyway.
Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/605
2017-03-31 10:36:58 -04:00
David Neto
2410e00851 Add low priority test suggestions for inliner 2017-03-29 18:02:40 -04:00
Greg Fischer
04fcc66743 Add exhaustive function call inlining to spirv-opt
Inlining is done for all functions designated as entry points.

Add optional validation to test fixture method SinglePassRunAndCheck.
2017-03-29 18:02:40 -04:00
David Neto
545a6c1dc3 Provide friendly names for true and false 2017-01-11 16:33:45 -05:00
David Neto
c935253c91 Make friendly number-based names for OpConstant
For example:
  %int_42 = OpConstant %int 42
  %int_n42 = OpConstant %int -42
  %float_3_14 = OpConstant %float 3.14
2016-11-15 14:05:03 -05:00
Lei Zhang
4f57e140bf Renaming test files to comply with Google style guide.
Also posfixing test files with `_test' to make it more clear.
2016-11-07 14:41:51 -05:00
Lei Zhang
c1d5e660ee Add begin() and end() for TypeManager. 2016-09-30 16:56:42 -04:00
Lei Zhang
f9cb7c282c Avoid appending EOL in StringifyMessage().
EOL should be appended when outputing to streams by the tool.
2016-09-23 15:13:24 -04:00
Lei Zhang
1ca817a38e Use nullptr as the default message consumer to ignore all messages.
There is no difference between the previous IgnoreMessage() function
and a null std::function, from functionality's perspective.
The user can set nullptr as the MessageConsumer, so need to guard
against nullptr before calling the consumer anyway. It's better
we use it internally so that it may expose problems by us instead
of the user.
2016-09-21 17:23:03 -04:00
Lei Zhang
6effeaa7f1 Change some asserts to normal errors in IrLoader. 2016-09-21 17:22:00 -04:00
Lei Zhang
620f05e679 Publish the C++ interface. 2016-09-21 14:41:47 -04:00
Lei Zhang
92411caa3b Rename SpvTools to SpirvTools. 2016-09-21 14:28:33 -04:00
Lei Zhang
1bc0b275dd Allow changing MessageConsumer in Pass & PassManager.
Default-constructed Pass/PassManager will have a MessageConsumer
which ignores all messages. SetMessageConsumer() should be called
to supply a meaningful MessageConsumer.
2016-09-20 16:48:00 -04:00
Lei Zhang
2cbb2cce3e Change interface of Pass::Process() to return possible failures. 2016-09-20 16:40:17 -04:00
Lei Zhang
8654caa565 Prepare the C++ interface for publication.
* Use PIMPL idiom in the C++ interface.
* Clean up interface for assembling and disassembling.
* Add validation into C++ interface.
* Add more tests for the C++ interface.
2016-09-16 16:37:27 -04:00
Lei Zhang
b54686d017 Move functions for building modules outside of the C++ interface. 2016-09-16 14:02:47 -04:00
Lei Zhang
114af21994 Add MessageConsumer to PassManager, Pass, and analysis interfaces.
Also convert some uses of assert() in optimization code to use
SPIRV_ASSERT(), SPIRV_UNIMPLEMENTED(), or SPIRV_UNREACHABLE()
accordingly.
2016-09-16 13:14:57 -04:00
qining
66f5b4bfc5 Build "spec id->default val str" mapping from string
Add function `ParseDefaultValuesString()` to build the spec id->default
value string mapping required by `SetSpecConstantDefaultValuePass`.
2016-09-14 12:26:34 -04:00
qining
abf57933ea Set default values for spec const decorated by SpecId
The pass instance is constructed with a map from spec id (uint32_t) to
default values in string format. The default value strings will be
parsed to numbers according to the target spec constant type.

If the Spec Id decoration is found to be applied on multiple different
target ids, that decoration instruction (OpDecorate or OpGroupDecorate)
will be skipped. But other decoration instrucitons may still be
processed.
2016-09-12 23:21:42 -04:00
qining
049f80f3b9 Add IsSigned() to opt::Analysis::Integer. 2016-09-08 19:32:20 -04:00
David Neto
9fc8658ef3 Relicense SPIRV-Tools under Apache 2.0
Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/383

Finalize v2016.4
2016-09-02 10:00:29 -04:00
Lei Zhang
2ad3b74fa3 Tests for preserving line debug insts even killing its affecting targets. 2016-09-01 11:51:09 -04:00
qining
eb60e2945a Unify constants pass
De-duplicate constants and unifies the uses of constants for a SPIR-V
module. If two constants are defined exactly the same, only one of them
will be kept and all the uses of the removed constant will be redirected
to the kept one.

This pass handles normal constants (defined with
OpConstant{|True|False|Composite}), some spec constants (those defined
with OpSpecConstant{Op|Composite}) and null constants (defined with
OpConstantNull).

There are several cases not handled by this pass:

  1) If there are decorations for the result id of a constant defining
  instruction, that instruction will not be processed. This means the
  instruction won't be used to replace other instructions and other
  instructions won't be used to replace it either.

  2) This pass does not unify null constants (defined with
  OpConstantNull instruction) with their equivalent zero-valued normal
  constants (defined with OpConstant{|False|Composite} with zero as the
  operand values or component values).
2016-09-01 11:46:05 -04:00
qining
2ce67252c8 Add forwarding so that passes' ctor can have args.
Also removed the default argument value of `skip_nop` for function
`SinglePassRunAndCheck()` and `SinglePassRunAndDisassemble()`. This is
required to support variadic arguments.
2016-08-31 15:27:55 -04:00
qining
76982706f9 Get annotation instructions of a given id. 2016-08-30 15:08:24 -04:00
qining
ecb5692389 Add AppendNames() interface for AssemblyBuilder 2016-08-29 17:18:31 -04:00
qining
380f36eae1 Fold spec constants to normal constants (values fixed)
For the spec constants defined by OpSpecConstantOp and
OpSpecContantComposite, if all of their operands are constants with
determined values (normal constants whose values are fixed), calculate
the correct values of the spec constants and re-define them as normal
constants.

In short, this pass replaces all the spec constants defined by
OpSpecContantOp and OpSpecConstantComposite with normal constants when
possible. So far not all valid operations of OpSpecConstantOp are
supported, we have several constriction here:

1) Only 32-bit integer and boolean (both scalar and vector) are
supported for any arithmetic operations. Integers in other width (like
64-bit) are not supported.
2) OpSConvert, OpFConvert, OpQuantizeToF16, and all the
operations under Kernel capability, are not supported.
3) OpCompositeInsert is not supported.

Note that this pass does not unify normal constants. This means it is
possible to have new generatd constants defining the same values.
2016-08-29 08:58:53 -04:00
David Neto
1d59aa0777 Pass manager recomputes Id bound automatically.
Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/371
in the sense that the id bound is correct after all the passes
have been run.  But it might be inconsistent between passes.
2016-08-27 13:19:18 -04:00
David Neto
d7b6362ed7 Add Module::ComputeIdBound
When IDs change, something should use this utility method
and Module::SetIdBound before writing out the binary.
2016-08-26 16:27:12 -04:00
Lei Zhang
0a175eb0d6 Add tests for decoration_empty(). 2016-08-26 14:05:04 -04:00
David Neto
58e1a1e3be Test ir::Instruction::GetOperand and GetInOperand 2016-08-26 10:59:25 -04:00
David Neto
cc60caba1d IrLoader gracefully handles incomplete blocks and functions
This lets us write smaller test cases with the IrLoader, avoiding
boilerplate for function begin/end, and basic block begin/end.

Also ForEachInst is more forgiving of cases where a basic block
doesn't have a label, and when a function doesn't have a defining
or end instruction.
2016-08-26 10:15:15 -04:00
David Neto
53013cc816 Add Instruction begin and end mutable iterators
Refactored the instuction test.
2016-08-25 17:48:58 -04:00
David Neto
2607bbf30b Add Instruction cbegin and cend to access operands 2016-08-25 15:24:32 -04:00
David Neto
97fc6aa3b8 ForEachInst optionally runs on attached debug line insts
Also:
- Add const forms of ForEachInst
- Rewrite Module::ToBinary in terms of ForEachInst
- Add Instruction::ToBinaryWithoutAttachedDebugInsts
- Delete the ToBinary method on Function, BasicBlock, and Instruction
  since it can now be implemented with ForEachInst in a less confusing
  way, e.g. without recursion.
- Preserve debug line instructions on OpFunctionEnd (and store that
  instruction as a unique-pointer, for regularity).
2016-08-25 11:43:22 -04:00
Lei Zhang
f51d82338e Add a home brewed make_unique to ease creating unique_ptrs. 2016-08-24 09:41:55 -04:00
David Neto
ccabcc4673 Add opt::ir::Module::SetIdBound 2016-08-23 15:20:34 -04:00
qining
7e775aa99e Get the number of elements for Vector and Matrix type 2016-08-23 11:34:24 -04:00
qining
b891845b53 Refine the DefUseManager
* Fix the behavior when analyzing an individual instruction:
  * exisiting instruction:
      Clear the original records and re-analyze it as a new instruction.
  * new instruction with exisiting result id:
      Clear the original records of the exisiting result id. This means
      the records of the analyzed result-id-defining instruction will be
      overwritten by the record of the new instruction with the same
      result id.
  * new instruction with new result id or without result id:
      Just update the internal records to incorperate the new
      instruction.
* Add tests for analyzing individual instruction w/o an exisiting module.
* Refactor ClearInst() implementation
* Remove ClearDef() function.
* Fixed a bug in DefUseManager::ReplaceAllUsesWith() that OpName
  instruction may trigger the assertion incorrectly.
* update the blurbs for EraseUseRecordsOfOperandIds()
2016-08-17 23:13:01 -04:00
qining
6c5bdc9a39 Get the width from integer and float type 2016-08-17 20:33:56 -04:00
Lei Zhang
b65124f097 Make clear that we are using ptrdiff_t as the iterator difference type.
And ptrdiff_t is a implementation defined signed type. Comparing it
with unsigned number literal causes compiler warnings.
2016-08-16 11:21:08 -04:00
Lei Zhang
9747d33d08 Derive iterator from std::iterator to reap standarad algorithms.
By deriving from std::iterator, iterator_traits will be properly
set up for our custom iterator type, thus we can use algorithms
from STL with our custom iterators.
2016-08-15 16:29:56 -04:00
Lei Zhang
1eec0ed4b9 Make analyses RAII-like and turn disable copy/move constructors. 2016-08-15 13:41:47 -04:00
Lei Zhang
097ff25ea7 Allow OpUndef appearing in the type and global variable section.
Also clean up API functions for adding instructions into the
type and global values section.
2016-08-15 10:44:14 -04:00
Lei Zhang
645ee1d9e0 Create an iterator class for in-memory representation. 2016-08-11 18:35:12 -04:00
qining
cd6d6c0ccf Add GetId(Type* type) API to the type manager 2016-08-11 15:10:09 -04:00
Lei Zhang
75d4316280 Fix build error about passing initializer-list to constructor.
VS2013 is not happy with using initializer-list to initialize
vector parameters to explicit constructors taking one vector.
2016-08-10 16:10:14 -04:00
Lei Zhang
dda9de965d Make type manager RAII-like w.r.t. the module to be analyzed. 2016-08-10 12:53:17 -04:00
Lei Zhang
c562e231e3 Optimization: Add type manager.
Type manager will construct a map of types gradually from
instructions.
2016-08-10 12:53:17 -04:00
Lei Zhang
6d4d15b9d0 Optimization: Add type class hierarchy. 2016-08-10 12:53:17 -04:00
Lei Zhang
80c94a4fa8 Change the interfaces of in-memory representation to use pointers.
Previously we use vectors of objects and move semantics to handle
ownership. That approach has the flaw that inserting an object into
the middle of a vector, which may trigger a vector reallocation,
can invalidate some addresses taken from instructions.

Now the in-memory representation internally uses vector of unique
pointers to handle ownership. Since objects are explicitly heap-
allocated now, pointers to them won't be invalidated by vector
resizing anymore.
2016-08-10 12:11:33 -04:00
Andrew Woloszyn
38c9471a0e Fixed the build for MSVC.
assembly_builder was missing an include for cstdint.
2016-08-10 09:45:15 -04:00
qining
d49928f0cc Fix minor mistakes in the tests of dead-const-elim 2016-08-09 14:37:58 -04:00
qining
a90fc84779 Print the shader when module building failed 2016-08-08 17:19:47 -04:00
qining
51a2484b36 Dead constant elimination
A pass to remove dead constants, including both front-end constants and spec
constants.

This pass does not handle dead variables and types.
2016-08-08 17:17:15 -04:00
qining
d37ecb924a Simple Assembly code builder for test uses
AssemblyBuilder contains boilplates.
Adds OpName instructions for all added defining instructions.
Adds OpDecorate SpecId for all spec constants added with OpSpecConstant,
OpSpecConstantTrue and OpSpecConstantFalse instructions.
2016-08-04 16:45:59 -04:00
Lei Zhang
64ff3c6dc1 Optimization: Add def use analysis. 2016-07-29 15:45:14 -04:00
qining
4750895943 Fix a test failure in pass manager test
Change "Null" to "null" in pass manager test
2016-07-28 15:30:37 -04:00
qining
a24506266b Freeze spec constants to their default values
Add a pass to freeze spec constants to their default values. This pass does
not fold the frozen spec constants and does not handle SpecConstantOp
instructions and SpecConstantComposite instructions.
2016-07-28 15:23:30 -04:00
qining
ac46512b05 Add an utility: in-place string replacement 2016-07-28 12:11:34 -04:00
qining
d503d75cc3 Use friendly disassembly output 2016-07-28 09:39:42 -04:00
Lei Zhang
2c4c73cf37 Add Pass, PassManager, and StripDebugInfoPass. 2016-06-29 17:32:00 -04:00
Lei Zhang
abf8f6413c Promote ir namespace and create draft libspirv.{h|c}pp. 2016-06-28 14:52:34 -04:00
Lei Zhang
8590f9cc81 Add IrBuilder for constructing SPIR-V in-memory representation. 2016-06-27 16:57:42 -04:00