Commit Graph

452 Commits

Author SHA1 Message Date
Lei Zhang 9cde4be7a5 [TableGen] Support creating multi-result ops in result patterns
This CL introduces a new syntax for creating multi-result ops and access their
results in result patterns. Specifically, if a multi-result op is unbound or
bound to a name without a trailing `__N` suffix, it will act as a value pack
and expand to all its values. If a multi-result op is bound to a symbol with
`__N` suffix, only the N-th result will be extracted and used.

PiperOrigin-RevId: 256465208
2019-07-03 18:17:49 -07:00
River Riddle 206e55cc16 NFC: Refactor Module to be value typed.
As with Functions, Module will soon become an operation, which are value-typed. This eases the transition from Module to ModuleOp. A new class, OwningModuleRef is provided to allow for owning a reference to a Module, and will auto-delete the held module on destruction.

PiperOrigin-RevId: 256196193
2019-07-02 16:43:36 -07:00
River Riddle 54cd6a7e97 NFC: Refactor Function to be value typed.
Move the data members out of Function and into a new impl storage class 'FunctionStorage'. This allows for Function to become value typed, which will greatly simplify the transition of Function to FuncOp(given that FuncOp is also value typed).

PiperOrigin-RevId: 255983022
2019-07-01 11:39:00 -07:00
Lei Zhang 2dc5e19426 Also disable generating underlying value to symbol conversion declaration when there is an enumerant without explicit value
PiperOrigin-RevId: 255950779
2019-07-01 09:56:11 -07:00
Lei Zhang 2652be7934 Avoid generating underlying value to symbol conversion function if there is an enumerant without explicit value.
PiperOrigin-RevId: 255945801
2019-07-01 09:55:59 -07:00
Lei Zhang 9dd182e0fa [ODS] Introduce IntEnumAttr
In ODS, right now we use StringAttrs to emulate enum attributes. It is
suboptimal if the op actually can and wants to store the enum as a
single integer value; we are paying extra cost on storing and comparing
the attribute value.

This CL introduces a new enum attribute subclass that are backed by
IntegerAttr. The downside with IntegerAttr-backed enum attributes is
that the assembly form now uses integer values, which is less obvious
than the StringAttr-backed ones. However, that can be remedied by
defining custom assembly form with the help of the conversion utility
functions generated via EnumsGen.

Choices are given to the dialect writers to decide which one to use for
their enum attributes.

PiperOrigin-RevId: 255935542
2019-07-01 09:55:47 -07:00
Lei Zhang 7b17f4e647 [spirv] Move conversion passes to a new library
PiperOrigin-RevId: 255648303
2019-06-28 12:32:02 -07:00
MLIR Team 7b5f49af76 Parenthesize match expression to avoid operator precedence issues
PiperOrigin-RevId: 255435454
2019-06-27 11:07:07 -07:00
Jacques Pienaar d4cf54f2c1 Split out TranslateClParser and add new parse method that reuses SourceMgr.
Split out class to command line parser for translate methods into standalone
class. Similar to splitting up mlir-opt to reuse functionality with different
initialization.

PiperOrigin-RevId: 255225790
2019-06-26 11:14:45 -07:00
Stephan Herhut c72c6c3907 Make GPU to CUDA transformations independent of CUDA runtime.
The actual transformation from PTX source to a CUDA binary is now factored out,
enabling compiling and testing the transformations independently of a CUDA
runtime.

MLIR has still to be built with NVPTX target support for the conversions to be
built and tested.

PiperOrigin-RevId: 255167139
2019-06-26 05:16:37 -07:00
Nicolas Vasilache dac75ae5ff Split test-specific passes out of mlir-opt
Instead put their impl in test/lib and link them into mlir-test-opt

PiperOrigin-RevId: 254837439
2019-06-24 17:47:12 -07:00
Jacques Pienaar 05c110adf3 Remove leftover change from splitting mlir-opt change.
PiperOrigin-RevId: 254767366
2019-06-24 13:45:53 -07:00
Jacques Pienaar 257a654b72 Split out mlir-opt main into separate file.
Enable reusing the real mlir-opt main from unit tests and in case where
additional initialization needs to happen before main is invoked (e.g., when
using different command line flag libraries).

PiperOrigin-RevId: 254764575
2019-06-24 13:45:39 -07:00
Lei Zhang 8f77d2afed [spirv] Basic serializer and deserializer
This CL adds the basic SPIR-V serializer and deserializer for converting
SPIR-V module into the binary format and back. Right now only an empty
module with addressing model and memory model is supported; (de)serialize
other components will be added gradually with subsequent CLs.

The purpose of this library is to enable importing SPIR-V binary modules
to run transformations on them and exporting SPIR-V modules to be consumed
by execution environments. The focus is transformations, which inevitably
means changes to the binary module; so it is not designed to be a general
tool for investigating the SPIR-V binary module and does not guarantee
roundtrip equivalence (at least for now).

PiperOrigin-RevId: 254473019
2019-06-22 09:17:21 -07:00
Mahesh Ravishankar d7ba69e811 Add SPIRV Image Type according to the spec described here :
https://www.khronos.org/registry/spir-v/specs/1.0/SPIRV.html#OpTypeImage.

Add new enums to describe Image dimensionality, Image Depth, Arrayed
information, Sampling, Sampler User information, and Image format.
Doesn's support the Optional Access qualifier at this stage

Fix Enum generator for tblgen to add "_" at the beginning if the enum
starts with a number.

PiperOrigin-RevId: 254091423
2019-06-19 23:09:01 -07:00
Lei Zhang 7848505ebd Print proper message saying variadic ops are not supported in RewriterGen
Support for ops with variadic operands/results will come later; but right now
a proper message helps to avoid deciphering confusing error messages later in
the compilation stage.

PiperOrigin-RevId: 254071820
2019-06-19 23:08:52 -07:00
Geoffrey Martin-Noble d7d69569e7 Rename -verify mlir-opt flag to -verify-expected-diagnostics
This name has caused some confusion because it suggests that it's running op verification (and that this verification isn't getting run by default).

PiperOrigin-RevId: 254035268
2019-06-19 23:08:03 -07:00
Stephan Herhut a14eeacf2c Add lowering pass from GPU dialect operations to LLVM/NVVM intrinsics.
PiperOrigin-RevId: 253551452
2019-06-19 23:03:30 -07:00
Alex Zinenko ebea5767fb Start moving conversions to {lib,include/mlir}/Conversion
Conversions from dialect A to dialect B depend on both A and B.  Therefore, it
is reasonable for them to live in a separate library that depends on both
DialectA and DialectB library, and does not forces dependees of DialectA or
DialectB to also link in the conversion.  Create the directory layout for the
conversions and move the Standard to LLVM dialect conversion as the first
example.

PiperOrigin-RevId: 253312252
2019-06-19 23:02:50 -07:00
River Riddle 3682936982 Disallow using NOperands/NResults when N < 2. We have special traits for the case of 0/1 that we explicitly check for throughout the codebase. This also fixes weird build failures in MSVC where it doesn't properly handle template type aliases.
PiperOrigin-RevId: 253269936
2019-06-19 23:02:40 -07:00
Alex Zinenko ee6f84aebd Convert a nest affine loops to a GPU kernel
This converts entire loops into threads/blocks.  No check on the size of the
block or grid, or on the validity of parallelization is performed, it is under
the responsibility of the caller to strip-mine the loops and to perform the
dependence analysis before calling the conversion.

PiperOrigin-RevId: 253189268
2019-06-19 23:02:02 -07:00
Lei Zhang a3e6f102ca [ODG] Fix value indices in verification error messages
we should use the dynamic index for the specific value instead
of the static one for ODS-declared values.

PiperOrigin-RevId: 252873052
2019-06-19 23:00:04 -07:00
Lei Zhang 6553b90c82 [ODG] Add support for private methods in class writers
PiperOrigin-RevId: 252602093
2019-06-11 10:14:11 -07:00
Lei Zhang 9e95e07987 [ODG] Address compiler warnings of comparing signed and unsigned integer expressions
PiperOrigin-RevId: 252442613
2019-06-11 10:12:44 -07:00
Lei Zhang 3812d956ea [ODS] Support variadic operand/result verification
This CL enables verification code generation for variadic operands and results.
In verify(), we use fallback getter methods to access all the dynamic values
belonging to one static variadic operand/result to reuse the value range
calculation there.

PiperOrigin-RevId: 252288219
2019-06-09 16:24:29 -07:00
Lei Zhang 7f108e60cc [ODG] Use getODSOperands() and getODSResults() to back accessors
This CL added getODSOperands() and getODSResults() as fallback getter methods for
getting all the dynamic values corresponding to a static operand/result (which
can be variadic). It should provide a uniform way of calculating the value ranges.
All named getter methods are layered on top of these methods now.

PiperOrigin-RevId: 252284270
2019-06-09 16:24:18 -07:00
Lei Zhang 1be9fc6611 [TableGen] Generating enum definitions and utility functions
Enum attributes can be defined using `EnumAttr`, which requires all its cases
to be defined with `EnumAttrCase`. To facilitate the interaction between
`EnumAttr`s and their C++ consumers, add a new EnumsGen TableGen backend
to generate a few common utilities, including an enum class, `llvm::DenseMapInfo`
for the enum class, conversion functions from/to strings.

This is controlled via the `-gen-enum-decls` and `-gen-enum-defs` command-line
options of `mlir-tblgen`.

PiperOrigin-RevId: 252209623
2019-06-09 16:24:08 -07:00
Jacques Pienaar 7438dcb71f ODG: Always deference operand/result when using named arg/result.
Considered adding more placeholders to designate types in the replacement pattern, but convinced for now sticking to simpler approach. This should at least enable specifying constraints across operands/results/attributes and we can start getting rid of the special cases.

PiperOrigin-RevId: 251564893
2019-06-09 16:18:10 -07:00
Alex Zinenko 252de8eca0 Introduce OpOperandAdaptors and emit them from ODS
When manipulating generic operations, such as in dialect conversion /
rewriting, it is often necessary to view a list of Values as operands to an
operation without creating the operation itself.  The absence of such view
makes dialect conversion patterns, among others, to use magic numbers to obtain
specific operands from a list of rewritten values when converting an operation.
Introduce XOpOperandAdaptor classes that wrap an ArrayRef<Value *> and provide
accessor functions identical to those available in XOp.  This makes it possible
for conversions to use these adaptors to address the operands with names rather
than rely on their position in the list.  The adaptors are generated from ODS
together with the actual operation definitions.

This is another step towards making dialect conversion patterns specific for a
given operation.

Illustrate the approach on conversion patterns in the standard to LLVM dialect
conversion.

PiperOrigin-RevId: 251232899
2019-06-03 19:26:12 -07:00
River Riddle 58e40178fc Remove the newline from the mlir-opt 'split-input-file' flag marker. This fixes support for DOS style new lines(/r/n).
--

PiperOrigin-RevId: 250899420
2019-06-01 20:12:11 -07:00
Jacques Pienaar 9c430353ae Disable named attribute in ODG for ArgOrResultElementTypeIs as was taking address of r-value.
--

PiperOrigin-RevId: 250805965
2019-06-01 20:11:51 -07:00
Lei Zhang 3650df50dd [ODS] Support region names and constraints
Similar to arguments and results, now we require region definition in ops to
    be specified as a DAG expression with the 'region' operator. This way we can
    specify the constraints for each region and optionally give the region a name.

    Two kinds of region constraints are added, one allowing any region, and the
    other requires a certain number of blocks.

--

PiperOrigin-RevId: 250790211
2019-06-01 20:11:42 -07:00
Jacques Pienaar 29073d999c Allow argument and result names replacement in predicates.
This allow specifying $x to refer to an operand's named argument (operand or attribute) or result. Skip variadic operands/results for now pending autogenerated discussion of their accessors.

    This adds a new predicate, following feedback on the naming but does not remove the old one. Post feedback I'll do that, potentially in follow up.

--

PiperOrigin-RevId: 250720003
2019-06-01 20:11:01 -07:00
Jacques Pienaar c59538977e Add keywords in target_link_libraries post add_llvm_executable.
--

PiperOrigin-RevId: 250704528
2019-06-01 20:10:42 -07:00
River Riddle 11e485ca19 Replace usages of 'add_executable' with 'add_llvm_executable'.
--

PiperOrigin-RevId: 250691487
2019-06-01 20:10:32 -07:00
Ben Vanik aa7ee31cbe [TableGen] Making printer support $cppClass substitution (similar to parser).
--

PiperOrigin-RevId: 250534216
2019-06-01 20:07:21 -07:00
Lei Zhang d4c8c8de42 [ODS] Support numRegions in Op definition
--

PiperOrigin-RevId: 250282024
2019-06-01 20:05:31 -07:00
Jacques Pienaar ffc4cf7091 Fix correspondence between trait names in ODS and C++ class names.
Make the correspondence between the ODS and C++ side clearer.

--

PiperOrigin-RevId: 250211194
2019-06-01 20:04:52 -07:00
Jacques Pienaar f0ee052d9e Use SourceMgrDiagnosticHandler in mlir-translate for translations from MLIR input.
Report errors using the file and line location using SourceMgr's diagnostic reporting. Reduce some horizontal white spacing too.

--

PiperOrigin-RevId: 250193646
2019-06-01 20:04:32 -07:00
Lei Zhang fba1d50b85 [spirv] Start the SPIR-V dialect
This CL sets up the basic structure for a SPIR-V dialect: operation
    definition specification, dialect registration, testing, etc.
    A single op, FMul, is defined and tested to showcase.

    The SPIR-V dialect aims to be a simple proxy for the SPIR-V binary format
    to enable straightforward and lightweight conversion from/to the binary
    format. Ops in this dialect should stay as the same semantic level and
    try to be a mechanical mapping to the corresponding SPIR-V instructions;
    but they can deviate representationally to allow using MLIR mechanisms.

--

PiperOrigin-RevId: 250040830
2019-06-01 20:03:33 -07:00
Jacques Pienaar 2f50b6c401 Use fused location for rewritten ops in generated rewrites.
This does tracks the location by recording all the ops in the source pattern and using the fused location for the transformed op. Track the locations via the rewrite state which is a bit heavy weight, in follow up to change to matchAndRewrite this will be addressed (and need for extra array go away).

--

PiperOrigin-RevId: 249986555
2019-06-01 20:03:12 -07:00
Jacques Pienaar b0a26768ec Make scope explicit to avoid misleading-indentation warnings.
--

PiperOrigin-RevId: 249986537
2019-06-01 20:03:02 -07:00
River Riddle 647f8cabb9 Add support to RewritePattern for specifying the potential operations that can be generated during a rewrite. This will enable analyses to start understanding the possible effects of applying a rewrite pattern.
--

PiperOrigin-RevId: 249936309
2019-06-01 20:02:42 -07:00
Jacques Pienaar 09438a412f Fix incorrect result type inference for nested tuples & remove hacky const case.
Builders can be further refined but wanted to address bug where the result type was used beyond the first depth.

--

PiperOrigin-RevId: 249936004
2019-06-01 20:02:33 -07:00
Jacques Pienaar 4165885a90 Add pattern file location to generated code to trace origin of pattern.
--

PiperOrigin-RevId: 249734666
2019-06-01 19:59:24 -07:00
Stella Laurenzo 5065839da7 Upstream the Quantizer tool (part 4).
This adds the basic passes needed and ties them into mlir-opt. Also adds two specific unit tests that exercise them.

    Next step is a standalone quantizer tool and additional cleanup.
    Tested:
      ninja check-mlir

--

PiperOrigin-RevId: 249167690
2019-06-01 19:53:12 -07:00
Lei Zhang 20e0cedfbd [ODS] Allow dialect to specify C++ namespaces
Previously we force the C++ namespaces to be `NS` if `SomeOp` is defined as
    `NS_SomeOp`. This is too rigid as it does not support nested namespaces
    well. This CL adds a "namespace" field into the Dialect class to allow
    flexible namespaces.

--

PiperOrigin-RevId: 249064981
2019-05-20 13:49:27 -07:00
Alex Zinenko 4408228269 ExecutionEngine: drop PassManager integration
Originally, ExecutionEngine was created before MLIR had a proper pass
    management infrastructure or an LLVM IR dialect (using the LLVM target
    directly).  It has been running a bunch of lowering passes to convert the input
    IR from Standard+Affine dialects to LLVM IR and, later, to the LLVM IR dialect.
    This is no longer necessary and is even undesirable for compilation flows that
    perform their own conversion to the LLVM IR dialect.  Drop this integration and
    make ExecutionEngine accept only the LLVM IR dialect.  Users of the
    ExecutionEngine can call the relevant passes themselves.

--

PiperOrigin-RevId: 249004676
2019-05-20 13:48:45 -07:00
River Riddle 1982afb145 Unify the 'constantFold' and 'fold' hooks on an operation into just 'fold'. This new unified fold hook will take constant attributes as operands, and may return an existing 'Value *' or a constant 'Attribute' when folding. This removes the awkward situation where a simple canonicalization like "sub(x,x)->0" had to be written as a canonicalization pattern as opposed to a fold.
--

PiperOrigin-RevId: 248582024
2019-05-20 13:44:24 -07:00
Nicolas Vasilache 6aa5cc8b06 Cleanup linalg integration test
This CL performs post-commit cleanups.
    It adds the ability to specify which shared libraries to load dynamically in ExecutionEngine. The linalg integration test is updated to use a shared library.
    Additional minor cleanups related to LLVM lowering of Linalg are also included.

--

PiperOrigin-RevId: 248346589
2019-05-20 13:43:13 -07:00
Stella Laurenzo d4dcf7de9e Move Quantization -> Dialect/QuantOps, FxpMathOps -> Dialect/FxpMathOps.
Adding the additional layer of directory was discussed offline and matches the Target/ tree. The names match the defacto convention we seem to be following where the C++ namespace is ^(.+)Ops/$ matched against the directory name.

    This is in preparation for patching the Quantizer into this tree, which would have been confusing without moving the Quantization dialect to its more proper home. It is left to others to move other dialects if desired.

    Tested:
      ninja check-mlir

--

PiperOrigin-RevId: 248171982
2019-05-20 13:41:55 -07:00
Jacques Pienaar c6c989f179 Move specification of print, parse and verify to Std_Op base.
Removes some boilerplate in ops, add support to refer to C++ class name from parser function specification in ODS.

--

PiperOrigin-RevId: 248140977
2019-05-20 13:41:29 -07:00
Nicolas Vasilache 5c64d2a6c4 Pipe Linalg to a cblas call via mlir-cpu-runner
This CL extends the execution engine to allow the additional resolution of symbols names
    that have been registered explicitly. This allows linking static library symbols that have not been explicitly exported with the -rdynamic linking flag (which is deemed too intrusive).

--

PiperOrigin-RevId: 247969504
2019-05-20 13:39:02 -07:00
River Riddle d7c467ded1 Remove the explicit "friend Operation" statement from each of the derived operations now that op casting is no longer inside of Operation.
--

PiperOrigin-RevId: 247791672
2019-05-20 13:38:02 -07:00
River Riddle d5b60ee840 Replace Operation::isa with llvm::isa.
--

PiperOrigin-RevId: 247789235
2019-05-20 13:37:52 -07:00
River Riddle c5ecf9910a Add support for using llvm::dyn_cast/cast/isa for operation casts and replace usages of Operation::dyn_cast with llvm::dyn_cast.
--

PiperOrigin-RevId: 247780086
2019-05-20 13:37:31 -07:00
MLIR Team 41d90a85bd Automated rollback of changelist 247778391.
PiperOrigin-RevId: 247778691
2019-05-20 13:37:20 -07:00
River Riddle 02e03b9bf4 Add support for using llvm::dyn_cast/cast/isa for operation casts and replace usages of Operation::dyn_cast with llvm::dyn_cast.
--

PiperOrigin-RevId: 247778391
2019-05-20 13:37:10 -07:00
Lei Zhang df5000fd31 [TableGen] Return base attribute's name for anonymous OptionalAttr/DefaultValuedAttr
--

PiperOrigin-RevId: 247693280
2019-05-10 19:30:48 -07:00
Mehdi Amini 8a34566515 Remove unused `signature()` from `OpMethod` class (private to mlir-tblgen) (NFC)
--

PiperOrigin-RevId: 247672280
2019-05-10 19:29:42 -07:00
Mehdi Amini a5ca314c4c Replace dyn_cast<> with isa<> when the returned value is unused (NFC)
Fix a gcc warning.

--

PiperOrigin-RevId: 247669360
2019-05-10 19:29:18 -07:00
Jacques Pienaar fa97d3a2cf Emit cast instead of dyn_cast_or_null where attribute is required.
If the attribute needs to exist for the validity of the op, then no need to use
    dyn_cast_or_null as the op would be invalid in the cases where cast fails, so
    just use cast.

--

PiperOrigin-RevId: 247617696
2019-05-10 19:28:29 -07:00
River Riddle 5fd4ec1b78 Move the diagnostic verification functionality out of mlir-opt and into a new llvm::SourceMgr diagnostic handler 'SourceMgrDiagnosticVerifierHandler'. This will allow for other tools to reuse the 'expected-*' functionality.
--

PiperOrigin-RevId: 247514684
2019-05-10 19:26:51 -07:00
Nicolas Vasilache 33449c3e6c Pipe Linalg to LLVM via mlir-cpu-runner
This CL adds support for functions in the Linalg dialect to run with mlir-cpu-runner.
    For this purpose, this CL adds BufferAllocOp, BufferDeallocOp, LoadOp and StoreOp to the Linalg dialect as well as their lowering to LLVM. To avoid collisions with mlir::LoadOp/StoreOp (which should really become mlir::affine::LoadOp/StoreOp), the mlir::linalg namespace is added.

    The execution uses a dummy linalg_dot function that just returns for now. In the future a proper library call will be used.

--

PiperOrigin-RevId: 247476061
2019-05-10 19:26:18 -07:00
River Riddle 4bc23a40f4 Add a utility diagnostic handler class, SourceMgrDiagnosticHandler, to interface with llvm::SourceMgr. This lowers the barrier of entry for tools to get rich diagnostic handling when using llvm::SourceMgr.
--

PiperOrigin-RevId: 247358610
2019-05-10 19:24:54 -07:00
River Riddle b7dc252683 NFC: Make ParseResult public and update the OpAsmParser(and thus all of the custom operation parsers) to use it instead of bool.
--

PiperOrigin-RevId: 246955523
2019-05-10 19:23:24 -07:00
Jacques Pienaar 7fea30b9dd Remove redundant ;
--

PiperOrigin-RevId: 246664861
2019-05-06 08:29:18 -07:00
River Riddle 3b930b0d70 Add explicit friendship with Operation to each derived op class to ensure access to the inherited protected constructor of `Op`. Some compiler versions have different rules for the visibility of inherited constructors.
--

PiperOrigin-RevId: 246661686
2019-05-06 08:28:50 -07:00
Jacques Pienaar 2fe8ae4f6c Fix up some mixed sign warnings.
--

PiperOrigin-RevId: 246614498
2019-05-06 08:28:20 -07:00
River Riddle b14c4b4ca8 Add support for basic remark diagnostics. This is the minimal functionality needed to separate notes from remarks. It also provides a starting point to start building out better remark infrastructure.
--

PiperOrigin-RevId: 246175216
2019-05-06 08:24:02 -07:00
River Riddle eaf7f6b671 Start sketching out a new diagnostics infrastructure. Create a new class 'DiagnosticEngine' and move the diagnostic handler support and final diagnostic emission from the MLIRContext to it.
--

PiperOrigin-RevId: 246163897
2019-05-06 08:23:53 -07:00
Smit Hinsu 0bd0571e72 Reserve the required capacity to avoid pointer invalidations for translation functions
--

PiperOrigin-RevId: 245992152
2019-05-06 08:23:04 -07:00
Stephan Herhut 5d7231d812 Add transformation of the NVVM dialect to an LLVM module. Only handles
the generation of intrinsics out of NVVM index ops for now.

--

PiperOrigin-RevId: 245933152
2019-05-06 08:22:14 -07:00
Jacques Pienaar 041e961802 Add extraClassDeclaration field for ops.
Simple mechanism to allow specifying arbitrary function declarations. The modelling will not cover all cases so allow a means for users to declare a method function that they will define in their C++ files. The goal is to allow full C++ flexibility as the goal is to cover cases not modelled.

--

PiperOrigin-RevId: 245889819
2019-05-06 08:21:58 -07:00
Jacques Pienaar 9fd1957852 Fix opt build failure.
--

PiperOrigin-RevId: 245844236
2019-05-06 08:21:25 -07:00
Jacques Pienaar 3ea13d2db0 Fixup MLIRGPU to mlir-opt in cmake.
--

PiperOrigin-RevId: 245820077
2019-05-06 08:21:09 -07:00
Nicolas Vasilache 56c7a957bf Parsing support for Range, View and Slice operations
This CL implements the previously unsupported parsing for Range, View and Slice operations.
    A pass is introduced to lower to the LLVM.
    Tests are moved out of C++ land and into mlir/test/Examples.
    This allows better fitting within standard developer workflows.

--

PiperOrigin-RevId: 245796600
2019-05-06 08:20:55 -07:00
Stephan Herhut 65ccb8cfd5 Add a new NVVM dialect that extends the LLVM dialect with some NVVM specific operations.
Currently, this is limited to operations that give access to the special registers of
    NVIDIA gpus that represent block and thread indices.

--

PiperOrigin-RevId: 245378632
2019-05-06 08:17:24 -07:00
Lei Zhang 6749c21d6e [TableGen] Support multiple variadic operands/results
Certain ops can have multiple variadic operands/results, e.g., `tf.DynamicStitch`.
    Even if an op has only one variadic operand/result, it is not necessarily the
    very last one, e.g., `tf.RaggedGather`. This CL enhances TableGen subsystem to be
    able to represent such cases.

    In order to deduce the operand/result value range for each variadic operand,
    currently we only support variadic operands/results all of the same size.
    So two new traits, `SameVariadicOperandSize` and `SameVariadicResultSize` are
    introduced.

--

PiperOrigin-RevId: 245310628
2019-05-06 08:16:54 -07:00
Lei Zhang 10bcc34a68 [TableGen] Clean up comments regarding op and result
An op can have multiple results. Being explicit that we are binding to the
    whole op instead of one of the results. A way to bind to a specific result
    is yet to come.

--

PiperOrigin-RevId: 244741137
2019-04-23 22:02:08 -07:00
Lei Zhang d0e2019d39 [TableGen] Unify cOp and tAttr into NativeCodeCall
Both cOp and tAttr were used to perform some native C++ code expression.
    Unifying them simplifies the concepts and reduces cognitive burden.

--

PiperOrigin-RevId: 244731946
2019-04-23 22:02:00 -07:00
Lei Zhang 09b623aa93 [TableGen] Capture bound source ops in PatternState
This allows accessing those bound source ops in result patterns, which can be
    useful for invoking native C++ op creation.

    We bind the op entirely here because ops can have multiple results. Design a
    approach to bind to a specific result is not the concern of this commit.

--

PiperOrigin-RevId: 244724750
2019-04-23 22:01:52 -07:00
Nicolas Vasilache 8370cc7492 Start a Linalg dialect
This CL starts implementing a Linalg dialect with the objective of supporting
    optimizing compilation of loops and library calls for a subset of common linear
    algebra operations.

    This CL starts by simply adding a linalg.range type and an operation with the
    proper roundtripping test.

--

PiperOrigin-RevId: 244189468
2019-04-18 11:50:27 -07:00
Lei Zhang 13285ee907 [TableGen] Simplify NOperands trait generation
--

PiperOrigin-RevId: 244162515
2019-04-18 11:50:11 -07:00
Lei Zhang b8dc04a005 [TableGen] Fix builder for ops with one variadic input and SameValueType
For ops with the SameValueType trait, we generate a builder without requiring
    result type; we get the result type from the operand. However, if the operand
    is variadic, we need to index into the first value in the pack.

--

PiperOrigin-RevId: 243866647
2019-04-18 11:48:42 -07:00
Lei Zhang 8bb8351710 [TableGen] Fix support for ops whose names have a leading underscore
TensorFlow ops have the convention to use leading underscore to denote
    internal ops.

--

PiperOrigin-RevId: 243627723
2019-04-18 11:48:17 -07:00
Smit Hinsu 0047ef9765 NFC: Simplify named attribute in TableGen generators
Now, op attribute names don't have '.' in their names so the special handling for it
    can be removed. Attributes for functions still have dialect prefix with '.' as separator but TableGen does not deal with functions.

    TESTED with existing unit tests

--

PiperOrigin-RevId: 243287462
2019-04-18 11:47:52 -07:00
Lei Zhang 138c972d11 [TableGen] Use `tgfmt` to format various predicates and rewrite rules
This CL changes various predicates and rewrite rules to use $-placeholders and
    `tgfmt` as the driver for substitution. This will make the predicates and rewrite
    rules more consistent regarding their arguments and more readable.

--

PiperOrigin-RevId: 243250739
2019-04-18 11:47:35 -07:00
Lei Zhang dfcc02b111 [TableGen] Support naming rewrite rules
--

PiperOrigin-RevId: 242909061
2019-04-11 10:52:43 -07:00
Lei Zhang bdd56eca49 Remove checks guaranteed to be true by the type
This addresses the compiler wraning of "comparison of unsigned expression
    >= 0 is always true [-Wtype-limits]".

--

PiperOrigin-RevId: 242868703
2019-04-11 10:52:33 -07:00
Lei Zhang 76cb205326 [TableGen] Enforce constraints on attributes
Previously, attribute constraints are basically unused: we set true for almost
    anything. This CL refactors common attribute kinds and sets constraints on
    them properly. And fixed verification failures found by this change.

    A noticeable one is that certain TF ops' attributes are required to be 64-bit
    integer, but the corresponding TFLite ops expect 32-bit integer attributes.
    Added bitwidth converters to handle this difference.

--

PiperOrigin-RevId: 241944008
2019-04-05 07:40:50 -07:00
Lei Zhang c7790df2ed [TableGen] Add PatternSymbolResolver for resolving symbols bound in patterns
We can bind symbols to op arguments/results in source pattern and op results in
    result pattern. Previously resolving these symbols is scattered across
    RewriterGen.cpp. This CL aggregated them into a `PatternSymbolResolver` class.

    While we are here, this CL also cleans up tests for patterns to make them more
    focused. Specifically, one-op-one-result.td is superseded by pattern.td;
    pattern-tAttr.td is simplified; pattern-bound-symbol.td is added for the change
    in this CL.

--

PiperOrigin-RevId: 241913973
2019-04-05 07:40:41 -07:00
Lei Zhang 3c833344c8 [TableGen] Rework verifier generation and error messages
Previously we bundle the existence check and the MLIR attribute kind check
    in one call. Further constraints (like element bitwidth) have to be split
    into following checks. That is not a nice separation given that we have more
    checks for constraints. Instead, this CL changes to generate a local variable
    for every attribute, check its existence first, then check the constraints.

    Creating a local variable for each attribute also avoids querying it multiple
    times using the raw getAttr() API. This is a win for both performance the
    readability of the generated code.

    This CL also changed the error message to be more greppable by delimiting
    the error message from constraints with boilerplate part with colon.

--

PiperOrigin-RevId: 241906132
2019-04-05 07:40:31 -07:00
Stella Laurenzo 7ce55ff7c2 Add CMakeLists.txt for Quantization and FxpMathOps dialects (and misc fixes to build with OSS setup).
Tested:
      cmake -G Ninja ../llvm/ -DLLVM_BUILD_EXAMPLES=ON
      ninja check-mlir

--

PiperOrigin-RevId: 241841296
2019-04-03 19:22:05 -07:00
Lei Zhang b9e3b2107b [TableGen] Allow additional result patterns not directly used for replacement
This CL looses the requirement that all result patterns in a rewrite rule must
    replace a result of the root op in the source pattern. Now only the last N
    result pattern-generated ops are used to replace a N-result source op.

    This allows to generate additional ops to aid building up final ops used to
    replace the source op.

--

PiperOrigin-RevId: 241783192
2019-04-03 19:20:22 -07:00
Lei Zhang 1ac49ce0bd [TableGen] Remove asserts for attributes in aggregate builders
Attributes can have default values or be optional. Checking the validity of
    attributes in aggregate builder should consider that. And to be accurate,
    we should check all required attributes are indeed provided in the list.
    This is actually duplicating the work done by verifier. Checking the validity
    of attributes should be the responsiblity of verifiers. This CL removes
    the assertion for attributes in aggregate builders for the above reason.
    (Assertions for operands/results are still kept since they are trivial.)

    Also added more tests for aggregate builders.

--

PiperOrigin-RevId: 241746059
2019-04-03 09:30:49 -07:00
River Riddle 67a52c44b1 Rewrite the verify hooks on operations to use LogicalResult instead of bool. This also changes the return of Operation::emitError/emitOpError to LogicalResult as well.
--

PiperOrigin-RevId: 241588075
2019-04-02 13:40:47 -07:00
River Riddle 0be6369176 Update the Function and Module verifiers to return LogicalResult instead of bool.
--

PiperOrigin-RevId: 241553930
2019-04-02 13:40:20 -07:00
Mehdi Amini b3a407fa68 Fix MacOS build
This is making up for some differences in standard library and linker flags.
    It also get rid of the requirement to build with RTTI.

--

PiperOrigin-RevId: 241348845
2019-04-01 11:00:30 -07:00
Lei Zhang b9e38a7972 [TableGen] Add EnumAttrCase and EnumAttr
This CL adds EnumAttr as a general mechanism for modelling enum attributes. Right now
    it is using StringAttr under the hood since MLIR does not have native support for enum
    attributes.

--

PiperOrigin-RevId: 241334043
2019-04-01 10:59:31 -07:00
Jacques Pienaar 1273af232c Add build files and update README.
* Add initial version of build files;
    * Update README with instructions to download and build MLIR from github;

--

PiperOrigin-RevId: 241102092
2019-03-30 11:23:22 -07:00
Feng Liu 5303587448 [TableGen] Support benefit score in pattern definition.
A integer number can be specified in the pattern definition and used as the
adjustment to the default benefit score in the generated rewrite pattern C++
definition.

PiperOrigin-RevId: 240994192
2019-03-29 17:55:55 -07:00
Dimitrios Vytiniotis 79bd6badb2 Remove global LLVM CLI variables from library code
Plus move parsing code into the MLIR CPU runner binary.

PiperOrigin-RevId: 240786709
2019-03-29 17:50:23 -07:00
River Riddle af9760fe18 Replace remaining usages of the Instruction class with Operation.
PiperOrigin-RevId: 240777521
2019-03-29 17:50:04 -07:00
Lei Zhang d5524388ab [TableGen] Change names for Builder* and OperationState* parameters to avoid collision
The `Builder*` parameter is unused in both generated build() methods so that we can
leave it unnamed. Changed stand-alone parameter build() to take `_tblgen_state` instead
of `result` to allow `result` to avoid having name collisions with op operand,
attribute, or result.

PiperOrigin-RevId: 240637700
2019-03-29 17:47:57 -07:00
Jacques Pienaar ed4fa52b4a Add missing numeric header for std::accumulate.
PiperOrigin-RevId: 240593135
2019-03-29 17:45:42 -07:00
River Riddle f9d91531df Replace usages of Instruction with Operation in the /IR directory.
This is step 2/N to renaming Instruction to Operation.

PiperOrigin-RevId: 240459216
2019-03-29 17:43:37 -07:00
Feng Liu c489f50e6f Add a trait to set the result type by attribute
Before this CL, the result type of the pattern match results need to be as same
as the first operand type, operand broadcast type or a generic tensor type.
This CL adds a new trait to set the result type by attribute. For example, the
TFL_ConstOp can use this to set the output type to its value attribute.

PiperOrigin-RevId: 240441249
2019-03-29 17:43:06 -07:00
River Riddle 96ebde9cfd Replace usages of "Op::operator->" with ".".
This is step 2/N of removing the temporary operator-> method as part of the de-const transition.

PiperOrigin-RevId: 240200792
2019-03-29 17:40:09 -07:00
Jacques Pienaar c8a311a788 Qualify string in OpDefinitionsGen. NFC.
PiperOrigin-RevId: 240188138
2019-03-29 17:39:52 -07:00
Lei Zhang 8f5fa56623 [TableGen] Consolidate constraint related concepts
Previously we have multiple mechanisms to specify op definition and match constraints:
TypeConstraint, AttributeConstraint, Type, Attr, mAttr, mAttrAnyOf, mPat. These variants
are not added because there are so many distinct cases we need to model; essentially,
they are all carrying a predicate. It's just an artifact of implementation.

It's quite confusing for users to grasp these variants and choose among them. Instead,
as the OpBase TableGen file, we need to strike to provide an unified mechanism. Each
dialect has the flexibility to define its own aliases if wanted.

This CL removes mAttr, mAttrAnyOf, mPat. A new base class, Constraint, is added. Now
TypeConstraint and AttrConstraint derive from Constraint. Type and Attr further derive
from TypeConstraint and AttrConstraint, respectively.

Comments are revised and examples are added to make it clear how to use constraints.

PiperOrigin-RevId: 240125076
2019-03-29 17:38:46 -07:00
Mehdi Amini bb621a5596 Using getContext() instead of getInstruction()->getContext() on Operation (NFC)
PiperOrigin-RevId: 240088209
2019-03-29 17:38:29 -07:00
Chris Lattner d9b5bc8f55 Remove OpPointer, cleaning up a ton of code. This also moves Ops to using
inherited constructors, which is cleaner and means you can now use DimOp()
to get a null op, instead of having to use Instruction::getNull<DimOp>().

This removes another 200 lines of code.

PiperOrigin-RevId: 240068113
2019-03-29 17:36:21 -07:00
Jacques Pienaar 7ab37aaf02 Fix missing parenthesis around negation.
This should probably be changed to instead use the negated form (e.g., get predicate + negate it + get resulting template), but this fixes it locally.

PiperOrigin-RevId: 240067116
2019-03-29 17:36:06 -07:00
Chris Lattner 986310a68f Remove const from Value, Instruction, Argument, and the various methods on the
*Op classes.  This is a net reduction by almost 400LOC.

PiperOrigin-RevId: 239972443
2019-03-29 17:34:33 -07:00
Jacques Pienaar b236041b93 Return operand_range instead for generated variadic operands accessor.
PiperOrigin-RevId: 239959381
2019-03-29 17:34:17 -07:00
Chris Lattner 5246bceee0 Now that ConstOpPointer is gone, we can change the various methods generated by
tblgen be non-const.  This requires introducing some const_cast's at the
moment, but those (and lots more stuff) will disappear in subsequent patches.

This significantly simplifies those patches because the various tblgen op emitters
get adjusted.

PiperOrigin-RevId: 239954566
2019-03-29 17:33:45 -07:00
Jacques Pienaar 4de7f95f7f Verify first body is not empty before testing last character.
Avoids sigabrt where body is empty.

PiperOrigin-RevId: 239942200
2019-03-29 17:33:30 -07:00
Chris Lattner 8d526ef173 Continue pushing const out of the IR types - removing the notion of a 'const
Module'.  NFC.

PiperOrigin-RevId: 239532885
2019-03-29 17:27:26 -07:00
Lei Zhang a09dc8a491 [TableGen] Generate op declaration and definition into different files
Previously we emit both op declaration and definition into one file and include it
in *Ops.h. That pulls in lots of implementation details in the header file and we
cannot hide symbols local to implementation. This CL splits them to provide a cleaner
interface.

The way how we define custom builders in TableGen is changed accordingly because now
we need to distinguish signatures and implementation logic. Some custom builders with
complicated logic now can be moved to be implemented in .cpp entirely.

PiperOrigin-RevId: 239509594
2019-03-29 17:26:26 -07:00
Jacques Pienaar 57270a9a99 Remove some statements that required >C++11, add includes and qualify names. NFC.
PiperOrigin-RevId: 239197784
2019-03-29 17:24:53 -07:00
Jacques Pienaar 1156b2df35 Cleanups for OSS build.
PiperOrigin-RevId: 238999629
2019-03-29 17:23:23 -07:00
Jacques Pienaar 509cd739bf Change Value to NamedTypeConstraint and use TypeConstraint.
Previously Value was a pair of name & Type, but for operands/result a TypeConstraint rather then a Type is specified. Update C++ side to match declarative side.

PiperOrigin-RevId: 238984799
2019-03-29 17:22:51 -07:00
Nicolas Vasilache a89d8c0a1a Port Tablegen'd reference implementation of Add to declarative builders.
PiperOrigin-RevId: 238977252
2019-03-29 17:22:36 -07:00
River Riddle 6810c8bdc1 Moving the IR printing and execution timing options out of mlir-opt and into lib/Pass. We now expose two methods: registerPassManagerCLOptions and applyPassManagerCLOptions; to allow for multiple different users (mlir-opt, etc.) to opt-in to this common functionality.
PiperOrigin-RevId: 238836911
2019-03-29 17:21:50 -07:00
Jacques Pienaar 14489b5a8a Remove unnecessary headers from mlir-opt.
PiperOrigin-RevId: 238639013
2019-03-29 17:20:12 -07:00
River Riddle 076a7350e2 Add an instrumentation for conditionally printing the IR before and after pass execution. This instrumentation can be added directly to the PassManager via 'enableIRPrinting'. mlir-opt exposes access to this instrumentation via the following flags:
* print-ir-before=(comma-separated-pass-list)
  - Print the IR before each of the passes provided within the pass list.
* print-ir-before-all
  - Print the IR before every pass in the pipeline.
* print-ir-after=(comma-separated-pass-list)
  - Print the IR after each of the passes provided within the pass list.
* print-ir-after-all
  - Print the IR after every pass in the pipeline.
* print-ir-module-scope
  - Always print the Module IR, even for non module passes.

PiperOrigin-RevId: 238523649
2019-03-29 17:19:57 -07:00
Feng Liu c52a812700 [TableGen] Support nested dag attributes arguments in the result pattern
Add support to create a new attribute from multiple attributes. It extended the
DagNode class to represent attribute creation dag. It also changed the
RewriterGen::emitOpCreate method to support this nested dag emit.

An unit test is added.

PiperOrigin-RevId: 238090229
2019-03-29 17:15:57 -07:00
River Riddle 6558f80c8d Refactor pass timing so that it is toggled on the passmanager via 'enableTiming'. This also makes the pipeline view the default display mode.
PiperOrigin-RevId: 238079916
2019-03-29 17:15:42 -07:00
River Riddle 0cc212f2b7 Ensure that pass timing is the last added pass instrumentation. This also updates the PassInstrumentor to iterate in reverse for the "after" hooks. This ensures that the instrumentations run in a stack like fashion.
PiperOrigin-RevId: 237840808
2019-03-29 17:11:56 -07:00
River Riddle e46ba31c66 Add a new instrumentation for timing pass and analysis execution. This is made available in mlir-opt via the 'pass-timing' and 'pass-timing-display' flags. The 'pass-timing-display' flag toggles between the different available display modes for the timing results. The current display modes are 'list' and 'pipeline', with 'list' representing the default.
Below shows the output for an example mlir-opt command line.

mlir-opt foo.mlir -verify-each=false -cse -canonicalize -cse -cse -pass-timing

list view (-pass-timing-display=list):
* In this mode the results are displayed in a list sorted by total time; with each pass/analysis instance aggregated into one unique result. This mode is similar to the output of 'time-passes' in llvm-opt.

===-------------------------------------------------------------------------===
                      ... Pass execution timing report ...
===-------------------------------------------------------------------------===
  Total Execution Time: 0.0097 seconds (0.0096 wall clock)

   ---User Time---   --System Time--   --User+System--   ---Wall Time---  --- Name ---
   0.0051 ( 58.3%)   0.0001 ( 12.2%)   0.0052 ( 53.8%)   0.0052 ( 53.8%)  Canonicalizer
   0.0025 ( 29.1%)   0.0005 ( 58.2%)   0.0031 ( 31.9%)   0.0031 ( 32.0%)  CSE
   0.0011 ( 12.6%)   0.0003 ( 29.7%)   0.0014 ( 14.3%)   0.0014 ( 14.2%)  DominanceInfo
   0.0087 (100.0%)   0.0009 (100.0%)   0.0097 (100.0%)   0.0096 (100.0%)  Total

pipeline view (-pass-timing-display=pipeline):
* In this mode the results are displayed in a nested pipeline view that mirrors the internal pass pipeline that is being executed in the pass manager. This view is useful for understanding specifically which parts of the pipeline are taking the most time, and can also be used to identify when analyses are being invalidated and recomputed.

===-------------------------------------------------------------------------===
                      ... Pass execution timing report ...
===-------------------------------------------------------------------------===
  Total Execution Time: 0.0082 seconds (0.0081 wall clock)

   ---User Time---   --System Time--   --User+System--   ---Wall Time---  --- Name ---
   0.0042 (100.0%)   0.0039 (100.0%)   0.0082 (100.0%)   0.0081 (100.0%)  Function Pipeline
   0.0005 ( 11.6%)   0.0008 ( 21.1%)   0.0013 ( 16.1%)   0.0013 ( 16.2%)    CSE
   0.0002 (  5.0%)   0.0004 (  9.3%)   0.0006 (  7.0%)   0.0006 (  7.0%)      (A) DominanceInfo
   0.0026 ( 61.8%)   0.0018 ( 45.6%)   0.0044 ( 54.0%)   0.0044 ( 54.1%)    Canonicalizer
   0.0005 ( 11.7%)   0.0005 ( 13.0%)   0.0010 ( 12.3%)   0.0010 ( 12.4%)    CSE
   0.0003 (  6.1%)   0.0003 (  8.3%)   0.0006 (  7.2%)   0.0006 (  7.1%)      (A) DominanceInfo
   0.0002 (  3.8%)   0.0001 (  2.8%)   0.0003 (  3.3%)   0.0003 (  3.3%)    CSE
   0.0042 (100.0%)   0.0039 (100.0%)   0.0082 (100.0%)   0.0081 (100.0%)  Total

PiperOrigin-RevId: 237825367
2019-03-29 17:11:25 -07:00
River Riddle 5e1f1d2cab Update the constantFold/fold API to use LogicalResult instead of bool.
PiperOrigin-RevId: 237719658
2019-03-29 17:10:50 -07:00
Jacques Pienaar 497d645337 Delete dead function.
Can reintroduce when needed.

PiperOrigin-RevId: 237599264
2019-03-29 17:09:35 -07:00
Lei Zhang 684cc6e8da [TableGen] Change to attach the name to DAG operator in result patterns
There are two ways that we can attach a name to a DAG node:

1) (Op:$name ...)
2) (Op ...):$name

The problem with 2) is that we cannot do it on the outmost DAG node in a tree.
Switch from 2) to 1).

PiperOrigin-RevId: 237513962
2019-03-29 17:08:05 -07:00
Lei Zhang 18fde7c9d8 [TableGen] Support multiple result patterns
This CL added the ability to generate multiple ops using multiple result
patterns, with each of them replacing one result of the matched source op.

Specifically, the syntax is

```
def : Pattern<(SourceOp ...),
              [(ResultOp1 ...), (ResultOp2 ...), (ResultOp3 ...)]>;
```

Assuming `SourceOp` has three results.

Currently we require that each result op must generate one result, which
can be lifted later when use cases arise.

To help with cases that certain output is unused and we don't care about it,
this CL also introduces a new directive: `verifyUnusedValue`. Checks will
be emitted in the `match()` method to make sure if the corresponding output
is not unused, `match()` returns with `matchFailure()`.

PiperOrigin-RevId: 237513904
2019-03-29 17:07:50 -07:00
River Riddle f427bddd06 Update the PassManager infrastructure to return Status instead of bool.
PiperOrigin-RevId: 237261205
2019-03-29 17:05:51 -07:00
Alex Zinenko dbaab04a80 TableGen most of the LLVM IR Dialect to LLVM IR conversions
The LLVM IR Dialect strives to be close to the original LLVM IR instructions.
The conversion from the LLVM IR Dialect to LLVM IR proper is mostly mechanical
and can be automated.  Implement TableGen support for generating conversions
from a concise pattern form in the TableGen definition of the LLVM IR Dialect
operations.  It is used for all operations except calls and branches.  These
operations need access to function and block remapping tables and would require
significantly more code to generate the conversions from TableGen definitions
than the current manually written conversions.

This implementation is accompanied by various necessary changes to the TableGen
operation definition infrastructure.  In particular, operation definitions now
contain named accessors to results as well as named accessors to the variadic
operand (returning a vector of operands).  The base operation support TableGen
file now contains a FunctionAttr definition.  The TableGen now allows to query
the names of the operation results.

PiperOrigin-RevId: 237203077
2019-03-29 17:04:50 -07:00
Lei Zhang 4fc9b51727 [TableGen] Emit verification code for op results
They can be verified using the same logic as operands.

PiperOrigin-RevId: 237101461
2019-03-29 17:02:26 -07:00
Alex Zinenko 95949a0d09 TableGen: allow mixing attributes and operands in the Arguments DAG of Op definition
The existing implementation of the Op definition generator assumes and relies
on the fact that native Op Attributes appear after its value-based operands in
the Arguments list.  Furthermore, the same order is used in the generated
`build` function for the operation.  This is not desirable for some operations
with mandatory attributes that would want the attribute to appear upfront for
better consistency with their textual representation, for example `cmpi` would
prefer the `predicate` attribute to be foremost in the argument list.

Introduce support for using attributes and operands in the Arguments DAG in no
particular order.  This is achieved by maintaining a list of Arguments that
point to either the value or the attribute and are used to generate the `build`
method.

PiperOrigin-RevId: 237002921
2019-03-29 16:59:35 -07:00
River Riddle 73e0297d36 Change the TensorFlow attribute prefix from "tf$" to "tf." to match the specification of dialect attributes. This also fixes tblgen generation of dialect attributes that used the sugared name "tf$attr" as c++ identifiers.
PiperOrigin-RevId: 236924392
2019-03-29 16:58:20 -07:00
Alex Zinenko dd75675080 TableGen: fix builder generation for optional attributes
The recently introduced support for generating MLIR Operations with optional
attributes did not handle the formatted string emission properly, in particular
it did not escape `{` and `}` in calls to `formatv` leading to assertions
during TableGen op definition generation.  Fix this by splitting out the
unncessary braces from the format string.  Additionally, fix the emission of
the builder argument comment to correctly indicate which attributes are indeed
optional and which are not.

PiperOrigin-RevId: 236832230
2019-03-29 16:56:50 -07:00
River Riddle 50efe0fc85 Add a 'verifyPasses' flag to the PassManager that specifies if the IR should be verified after each pass. This also adds a "verify-each" flag to mlir-opt to optionally disable running the verifier after each pass.
PiperOrigin-RevId: 236703760
2019-03-29 16:55:35 -07:00
River Riddle ed5fe2098b Remove PassResult and have the runOnFunction/runOnModule functions return void instead. To signal a pass failure, passes should now invoke the 'signalPassFailure' method. This provides the equivalent functionality when needed, but isn't an intrusive part of the API like PassResult.
PiperOrigin-RevId: 236202029
2019-03-29 16:50:44 -07:00
Alex Zinenko d9cc3c31cc ExecutionEngine OptUtils: support -On flags in string-based initialization
Original implementation of OutUtils provided two different LLVM IR module
transformers to be used with the MLIR ExecutionEngine: OptimizingTransformer
parameterized by the optimization levels (similar to -O3 flags) and
LLVMPassesTransformer parameterized by the string formatted similarly to
command line options of LLVM's "opt" tool without support for -O* flags.
Introduce such support by declaring the flags inside the parser and by
populating the pass managers similarly to what "opt" does.  Remove the
additional flags from mlir-cpu-runner as they can now be wrapped into
`-llvm-opts` together with other LLVM-related flags.

PiperOrigin-RevId: 236107292
2019-03-29 16:49:44 -07:00
River Riddle 091ff3dc3f Add support for registering pass pipelines to the PassRegistry. This is done by providing a static registration facility PassPipelineRegistration that works similarly to PassRegistration except for it also takes a function that will add necessary passes to a provided PassManager.
void pipelineBuilder(PassManager &pm) {
      pm.addPass(new MyPass());
      pm.addPass(new MyOtherPass());
  }

  static PassPipelineRegistration Unused("unused", "Unused pass", pipelineBuilder);

This is also useful for registering specializations of existing passes:

  Pass *createFooPass10() { return new FooPass(10); }

  static PassPipelineRegistration Unused("unused", "Unused pass", createFooPass10);

PiperOrigin-RevId: 235996282
2019-03-29 16:48:29 -07:00
River Riddle c6c534493d Port all of the existing passes over to the new pass manager infrastructure. This is largely NFC.
PiperOrigin-RevId: 235952357
2019-03-29 16:47:14 -07:00
Lei Zhang 493d46067b [TableGen] Use result names in build() methods if possible
This will make it clear which result's type we are expecting in the build() signature.

PiperOrigin-RevId: 235925706
2019-03-29 16:46:41 -07:00
Lei Zhang bac3eece66 [TableGen] Fix using rewrite()'s qualified name for a bound argument in match()
PiperOrigin-RevId: 235767304
2019-03-29 16:44:05 -07:00
Smit Hinsu fd3c2d156f Verify IR produced by TranslateToMLIR functions
TESTED with existing unit tests

PiperOrigin-RevId: 235623059
2019-03-29 16:42:35 -07:00
Lei Zhang 3f644705eb [TableGen] Use ArrayRef instead of SmallVectorImpl for suitable method
PiperOrigin-RevId: 235577399
2019-03-29 16:41:35 -07:00
Stella Laurenzo c81b16e279 Spike to define real math ops and lowering of one variant of add to corresponding integer ops.
The only reason in starting with a fixedpoint add is that it is the absolute simplest variant and illustrates the level of abstraction I'm aiming for.

The overall flow would be:
  1. Determine quantization parameters (out of scope of this cl).
  2. Source dialect rules to lower supported math ops to the quantization dialect (out of scope of this cl).
  3. Quantization passes: [-quant-convert-const, -quant-lower-uniform-real-math, -quant-lower-unsupported-to-float] (the last one not implemented yet)
  4. Target specific lowering of the integral arithmetic ops (roughly at the level of gemmlowp) to more fundamental operations (i.e. calls to gemmlowp, simd instructions, DSP instructions, etc).

How I'm doing this should facilitate implementation of just about any kind of backend except TFLite, which has a very course, adhoc surface area for its quantized kernels. Options there include (I'm not taking an opinion on this - just trying to provide options):
  a) Not using any of this: just match q/dbarrier + tf math ops to the supported TFLite quantized op set.
  b) Implement the more fundamental integer math ops on TFLite and convert to those instead of the current op set.

Note that I've hand-waved over the process of choosing appropriate quantization parameters. Getting to that next. As you can see, different implementations will likely have different magic combinations of specific math support, and we will need the target system that has been discussed for some of the esoteric cases (i.e. many DSPs only support POT fixedpoint).

Two unrelated changes to the overall goal of this CL and can be broken out of desired:
  - Adding optional attribute support to TabelGen
  - Allowing TableGen native rewrite hooks to return nullptr, signalling that no rewrite has been done.

PiperOrigin-RevId: 235267229
2019-03-29 16:39:13 -07:00
Jacques Pienaar 1725b485eb Create OpTrait base class & allow operation predicate OpTraits.
* Introduce a OpTrait class in C++ to wrap the TableGen definition;
* Introduce PredOpTrait and rename previous usage of OpTrait to NativeOpTrait;
* PredOpTrait allows specifying a trait of the operation by way of predicate on the operation. This will be used in future to create reusable set of trait building blocks in the definition of operations. E.g., indicating whether to operands have the same type and allowing locally documenting op requirements by trait composition.
  - Some of these building blocks could later evolve into known fixed set as LLVMs backends do, but that can be considered with more data.
* Use the modelling to address one verify TODO in a very local manner.

This subsumes the current custom verify specification which will be removed in a separate mechanical CL.

PiperOrigin-RevId: 234827169
2019-03-29 16:35:11 -07:00
River Riddle 48ccae2476 NFC: Refactor the files related to passes.
* PassRegistry is split into its own source file.
* Pass related files are moved to a new library 'Pass'.

PiperOrigin-RevId: 234705771
2019-03-29 16:32:56 -07:00
Lei Zhang e0fc503896 [TableGen] Support using Variadic<Type> in results
This CL extended TableGen Operator class to provide accessors for information on op
results.

In OpDefinitionGen, added checks to make sure only the last result can be variadic,
and adjusted traits and builders generation to consider variadic results.

PiperOrigin-RevId: 234596124
2019-03-29 16:31:11 -07:00
Lei Zhang 911b9960ba [TableGen] Fix discrepancy between parameter meaning and code logic
The parameter to emitStandaloneParamBuilder() was renamed from hasResultType to
isAllSameType, which is the opposite boolean value. The logic should be changed
to make them consistent.

Also re-ordered some methods in Operator. And few other tiny improvements.

PiperOrigin-RevId: 234478316
2019-03-29 16:30:41 -07:00
Alex Zinenko 4bb31f7377 ExecutionEngine: provide utils for running CLI-configured LLVM passes
A recent change introduced a possibility to run LLVM IR transformation during
JIT-compilation in the ExecutionEngine.  Provide helper functions that
construct IR transformers given either clang-style optimization levels or a
list passes to run.  The latter wraps the LLVM command line option parser to
parse strings rather than actual command line arguments.  As a result, we can
run either of

    mlir-cpu-runner -O3 input.mlir
    mlir-cpu-runner -some-mlir-pass -llvm-opts="-llvm-pass -other-llvm-pass"

to combine different transformations.  The transformer builder functions are
provided as a separate library that depends on LLVM pass libraries unlike the
main execution engine library.  The library can be used for integrating MLIR
execution engine into external frameworks.

PiperOrigin-RevId: 234173493
2019-03-29 16:29:41 -07:00
Lei Zhang 081299333b [TableGen] Rename Operand to Value to prepare sharing between operand and result
We specify op operands and results in TableGen op definition using the same syntax.
They should be modelled similarly in TableGen driver wrapper classes.

PiperOrigin-RevId: 234153332
2019-03-29 16:29:11 -07:00
Lei Zhang 93d8f14c0f [TFLite] Fuse AddOp into preceding convolution ops
If we see an add op adding a constant value to a convolution op with constant
bias, we can fuse the add into the convolution op by constant folding the
bias and the add op's constant operand.

This CL also removes dangling RewriterGen check that prevents us from using
nested DAG nodes in result patterns, which is already supported.

PiperOrigin-RevId: 233989654
2019-03-29 16:27:55 -07:00
Lei Zhang eb3f8dcb93 [TableGen] Use deduced result types for build() of suitable ops
For ops with the SameOperandsAndResultType trait, we know that all result types
should be the same as the first operand's type. So we can generate a build()
method without requiring result types as parameters and also invoke this method
when constructing such ops during expanding rewrite patterns.

Similarly for ops have broadcast behavior, we can define build() method to use
the deduced type as the result type. So we can also calling into this build()
method when constructing ops in RewriterGen.

PiperOrigin-RevId: 233988307
2019-03-29 16:27:40 -07:00
Alex Zinenko 50700b8122 Reimplement LLVM IR translation to use the MLIR LLVM IR dialect
Original implementation of the translation from MLIR to LLVM IR operated on the
Standard+BuiltIn dialect, with a later addition of the SuperVector dialect.
This required the translation to be aware of a potetially large number of other
dialects as the infrastructure extended.  With the recent introduction of the
LLVM IR dialect into MLIR, the translation can be switched to only translate
the LLVM IR dialect, and the translation of the operations becomes largely
mechanical.

The reimplementation of the translator follows the lines of the original
translator in function and basic block conversion.  In particular, block
arguments are converted to LLVM IR PHI nodes, which are connected to their
sources after all blocks of a function had been converted.  Thanks to LLVM IR
types being wrapped in the MLIR LLVM dialect type, type conversion is
simplified to only convert function types, all other types are simply
unwrapped.  Individual instructions are constructed using the LLVM IRBuilder,
which has a great potential for being table-generated from the LLVM IR dialect
operation definitions.

The input of the test/Target/llvmir.mlir is updated to use the MLIR LLVM IR
dialect.  While it is now redundant with the dialect conversion test, the point
of the exercise is to guarantee exactly the same LLVM IR is emitted.  (Only the
name of the allocation function is changed from `__mlir_alloc` to `alloc` in
the CHECK lines.)  It will be simplified in a follow-up commit.

PiperOrigin-RevId: 233842306
2019-03-29 16:27:10 -07:00
Jacques Pienaar 388fb3751e Add pattern constraints.
Enable matching pattern only if constraint is met. Start with type constraints and more general C++ constraints.

PiperOrigin-RevId: 233830768
2019-03-29 16:26:53 -07:00
Lei Zhang de0fffdb5f [TFLite] Add rewrite pattern to fuse conv ops with Relu6 op
* Fixed tfl.conv_2d and tfl.depthwise_conv_2d to have fused activation
  function attribute
* Fixed RewriterGen crash: trying to get attribute match template when
  the matcher is unspecified (UnsetInit)

PiperOrigin-RevId: 233241755
2019-03-29 16:23:23 -07:00
Lei Zhang a9cee4fc8c [TableGen] Support nested DAG nodes in result result op arguments
This CL allowed developers to write result ops having nested DAG nodes as their
arguments. Now we can write

```
def : Pat<(...), (AOp (BOp, ...), AOperand)>
```
PiperOrigin-RevId: 233207225
2019-03-29 16:23:08 -07:00
Lei Zhang a57b398906 [TableGen] Assign created ops to variables and rewrite with PatternRewriter::replaceOp()
Previously we were using PatternRewrite::replaceOpWithNewOp() to both create the new op
inline and rewrite the matched op. That does not work well if we want to generate multiple
ops in a sequence. To support that, this CL changed to assign each newly created op to a
separate variable.

This CL also refactors how PatternEmitter performs the directive dispatch logic.

PiperOrigin-RevId: 233206819
2019-03-29 16:22:53 -07:00
Jacques Pienaar 351eed0dd1 Add tf.LeakyRelu.
* Add tf.LeakyRelu op definition + folders (well one is really canonicalizer)
* Change generated error message to use attribute description instead;
* Change the return type of F32Attr to be APFloat - internally it is already
  stored as APFloat so let the caller decides if they want to convert it or
  not. I could see varying opinions here though :) (did not change i32attr
  similarly)

PiperOrigin-RevId: 232923358
2019-03-29 16:20:53 -07:00
Lei Zhang 1df6ca5053 [TableGen] Model variadic operands using Variadic<Type>
Previously, we were using the trait mechanism to specify that an op has variadic operands.
That led a discrepancy between how we handle ops with deterministic number of operands.
Besides, we have no way to specify the constraints and match against the variadic operands.

This CL introduced Variadic<Type> as a way to solve the above issues.

PiperOrigin-RevId: 232656104
2019-03-29 16:16:28 -07:00
River Riddle 870d778350 Begin the process of fully removing OperationInst. This patch cleans up references to OperationInst in the /include, /AffineOps, and lib/Analysis.
PiperOrigin-RevId: 232199262
2019-03-29 16:09:36 -07:00
River Riddle de2d0dfbca Fold the functionality of OperationInst into Instruction. OperationInst still exists as a forward declaration and will be removed incrementally in a set of followup cleanup patches.
PiperOrigin-RevId: 232198540
2019-03-29 16:09:19 -07:00
Lei Zhang b2dbbdb704 Merge OpProperty and Traits into OpTrait
They are essentially both modelling MLIR OpTrait; the former achieves the
purpose via introducing corresponding symbols in TableGen, while the latter
just uses plain strings.

Unify them to provide a single mechanism to avoid confusion and to better
reflect the definitions on MLIR C++ side.

Ideally we should be able to deduce lots of these traits automatically via
other bits of op definitions instead of manually specifying them; but not
for now though.

PiperOrigin-RevId: 232191401
2019-03-29 16:09:03 -07:00
Lei Zhang e0774c008f [TableGen] Use tblgen::DagLeaf to model DAG arguments
This CL added a tblgen::DagLeaf wrapper class with several helper methods for handling
DAG arguments. It helps to refactor the rewriter generation logic to be more higher
level.

This CL also added a tblgen::ConstantAttr wrapper class for constant attributes.

PiperOrigin-RevId: 232050683
2019-03-29 16:06:31 -07:00
Nicolas Vasilache 0353ef99eb Cleanup EDSCs and start a functional auto-generated library of custom Ops
This CL applies the following simplifications to EDSCs:
1. Rename Block to StmtList because an MLIR Block is a different, not yet
supported, notion;
2. Rework Bindable to drop specific storage and just use it as a simple wrapper
around Expr. The only value of Bindable is to force a static cast when used by
the user to bind into the emitter. For all intended purposes, Bindable is just
a lightweight check that an Expr is Unbound. This simplifies usage and reduces
the API footprint. After playing with it for some time, it wasn't worth the API
cognition overhead;
3. Replace makeExprs and makeBindables by makeNewExprs and copyExprs which is
more explicit and less easy to misuse;
4. Add generally useful functionality to MLIREmitter:
  a. expose zero and one for the ubiquitous common lower bounds and step;
  b. add support to create already bound Exprs for all function arguments as
  well as shapes and views for Exprs bound to memrefs.
5. Delete Stmt::operator= and replace by a `Stmt::set` method which is more
explicit.
6. Make Stmt::operator Expr() explicit.
7. Indexed.indices assertions are removed to pave the way for expressing slices
and views as well as to work with 0-D memrefs.

The CL plugs those simplifications with TableGen and allows emitting a full MLIR function for
pointwise add.

This "x.add" op is both type and rank-agnostic (by allowing ArrayRef of Expr
passed to For loops) and opens the door to spinning up a composable library of
existing and custom ops that should automate a lot of the tedious work in
TF/XLA -> MLIR.

Testing needs to be significantly improved but can be done in a separate CL.

PiperOrigin-RevId: 231982325
2019-03-29 16:05:23 -07:00
Jacques Pienaar 82dc6a878c Add fallback to native code op builder specification for patterns.
This allow for arbitrarily complex builder patterns which is meant to cover initial cases while the modelling is improved and long tail cases/cases for which expanding the DSL would result in worst overall system.

NFC just sorting the emit replace methods alphabetical in the class and file body.

PiperOrigin-RevId: 231890352
2019-03-29 16:04:53 -07:00
Jacques Pienaar 4161d44bd5 Enable using constant attribute as matchers.
Straight roll-forward of cl/231322019 that got accidentally reverted in the move.

PiperOrigin-RevId: 231791464
2019-03-29 16:04:38 -07:00
Lei Zhang 66647a313a [tablegen] Use tblgen:: classes for NamedAttribute and Operand fields
This is another step towards hiding raw TableGen API calls.

PiperOrigin-RevId: 231580827
2019-03-29 16:02:23 -07:00
Lei Zhang b7d2e32c84 [doc] Use table to list all attributes
For each attribute, list its MLIR type and description.

PiperOrigin-RevId: 231580353
2019-03-29 16:02:08 -07:00
Lei Zhang 726dc08e4d [doc] Generate more readable description for attributes
This CL added "description" field to AttrConstraint and Attr, like what we
have for type classes.

PiperOrigin-RevId: 231579853
2019-03-29 16:01:53 -07:00
Lei Zhang 18219caeb2 [doc] Generate more readable description for operands
This CL mandated TypeConstraint and Type to provide descriptions and fixed
various subclasses and definitions to provide so. The purpose is to enforce
good documentation; using empty string as the default just invites oversight.

PiperOrigin-RevId: 231579629
2019-03-29 16:01:38 -07:00
Lei Zhang a759cf3190 Include op results in generate TensorFlow/TFLite op docs
* Emitted result lists for ops.
* Changed to allow empty summary and description for ops.
* Avoided indenting description to allow proper MarkDown rendering of
  formatting markers inside description content.
* Used fixed width font for operand/attribute names.
* Massaged TensorFlow op docs and generated dialect op doc.

PiperOrigin-RevId: 231427574
2019-03-29 16:00:53 -07:00
Lei Zhang c224a518f5 TableGen: Use DAG for op results
Similar to op operands and attributes, use DAG to specify operation's results.
This will allow us to provide names and matchers for outputs.

Also Defined `outs` as a marker to indicate the start of op result list.

PiperOrigin-RevId: 231422455
2019-03-29 16:00:22 -07:00
Lei Zhang 1dfc3ac5ce Prefix Operator getter methods with "get" to be consistent
PiperOrigin-RevId: 231416230
2019-03-29 15:59:46 -07:00
Nicolas Vasilache 0f9436e56a Move google-mlir to google_mlir
Python modules cannot be defined under a directory that has a `-` character in its name inside of Google code.
Rename to `google_mlir` which circumvents this limitation.

PiperOrigin-RevId: 231329321
2019-03-29 15:42:55 -07:00
Jacques Pienaar ad637f3cce Enable using constant attribute as matchers.
Update to allow constant attribute values to be used to match or as result in rewrite rule. Define variable ctx in the matcher to allow matchers to refer to the context of the operation being matched.

PiperOrigin-RevId: 231322019
2019-03-29 15:42:23 -07:00
Lei Zhang eb753f4aec Add tblgen::Pattern to model Patterns defined in TableGen
Similar to other tblgen:: abstractions, tblgen::Pattern hides the native TableGen
API and provides a nicer API that is more coherent with the TableGen definitions.

PiperOrigin-RevId: 231285143
2019-03-29 15:41:38 -07:00
Jacques Pienaar 0fbf4ff232 Define mAttr in terms of AttrConstraint.
* Matching an attribute and specifying a attribute constraint is the same thing executionally, so represent it such.
* Extract AttrConstraint helper to match TypeConstraint and use that where mAttr was previously used in RewriterGen.

PiperOrigin-RevId: 231213580
2019-03-29 15:41:23 -07:00
Lei Zhang ba1715f407 Pull TableGen op argument definitions into their own files
PiperOrigin-RevId: 230923050
2019-03-29 15:36:52 -07:00
Lei Zhang 2de5e9fd19 Support op removal patterns in TableGen
This CL adds a new marker, replaceWithValue, to indicate that no new result
op is generated by applying a pattern. Instead, the matched DAG is replaced
by an existing SSA value.

Converted the tf.Identity converter to use the pattern.

PiperOrigin-RevId: 230922323
2019-03-29 15:36:37 -07:00
Alex Zinenko 5a4403787f Simple CPU runner
This implements a simple CPU runner based on LLVM Orc JIT.  The base
functionality is provided by the ExecutionEngine class that compiles and links
the module, and provides an interface for obtaining function pointers to the
JIT-compiled MLIR functions and for invoking those functions directly.  Since
function pointers need to be casted to the correct pointer type, the
ExecutionEngine wraps LLVM IR functions obtained from MLIR into a helper
function with the common signature `void (void **)` where the single argument
is interpreted as a list of pointers to the actual arguments passed to the
function, eventually followed by a pointer to the result of the function.
Additionally, the ExecutionEngine is set up to resolve library functions to
those available in the current process, enabling support for, e.g., simple C
library calls.

For integration purposes, this also provides a simplistic runtime for memref
descriptors as expected by the LLVM IR code produced by MLIR translation.  In
particular, memrefs are transformed into LLVM structs (can be mapped to C
structs) with a pointer to the data, followed by dynamic sizes.  This
implementation only supports statically-shaped memrefs of type float, but can
be extened if necessary.

Provide a binary for the runner and a test that exercises it.

PiperOrigin-RevId: 230876363
2019-03-29 15:36:08 -07:00
Chris Lattner 934b6d125f Introduce a new operation hook point for implementing simple local
canonicalizations of operations.  The ultimate important user of this is
going to be a funcBuilder->foldOrCreate<YourOp>(...) API, but for now it
is just a more convenient way to write certain classes of canonicalizations
(see the change in StandardOps.cpp).

NFC.

PiperOrigin-RevId: 230770021
2019-03-29 15:34:35 -07:00
Jacques Pienaar f20ec77be1 Fixing op description white space during doc emission.
Strip additional whitespacing before and only add required additional indentation back.

PiperOrigin-RevId: 230426127
2019-03-29 15:31:20 -07:00
Jacques Pienaar 34c6f8c6e4 Add default attr value & define tf.AvgPool op and use pattern for rewrite.
Add default values to attributes, to allow attribute being left unspecified.  The attr getter will always return an attribute so callers need not check for it, if the attribute is not set then the default will be returned (at present the default will be constructed upon query but this will be changed).

Add op definition for tf.AvgPool in ops.td, rewrite matcher using pattern using attribute matching & transforms. Adding some helper functions to make it simpler.

Handle attributes with dialect prefix and map them to getter without dialect prefix.

Note: VerifyAvgPoolOp could probably be autogenerated by know given the predicate specification on attributes, but deferring that to a follow up.
PiperOrigin-RevId: 230364857
2019-03-29 15:29:59 -07:00
Jacques Pienaar a280e3997e Start doc generation pass.
Start doc generation pass that generates simple markdown output. The output is formatted simply[1] in markdown, but this allows seeing what info we have, where we can refine the op description (e.g., the inputs is probably redundant), what info is missing (e.g., the attributes could probably have a description).

The formatting of the description is still left up to whatever was in the op definition (which luckily, due to the uniformity in the .td file, turned out well but relying on the indentation there is fragile). The mechanism to autogenerate these post changes has not been added yet either. The output file could be run through a markdown formatter too to remove extra spaces.

[1]. This is not proposal for final style :) There could also be a discussion around single doc vs multiple (per dialect, per op), whether we want a TOC, whether operands/attributes should be headings or just formatted differently ...

PiperOrigin-RevId: 230354538
2019-03-29 15:29:29 -07:00
Jacques Pienaar d6f84fa5d9 Add AttrConstraint to enable generating verification for attribute values.
Change MinMaxAttr to match hasValidMinMaxAttribute behavior. Post rewriting the other users of that function it could be removed too. The currently generated error message is:

error: 'tfl.fake_quant' op attribute 'minmax' failed to satisfy constraint of MinMaxAttr
PiperOrigin-RevId: 229775631
2019-03-29 15:25:13 -07:00
Jacques Pienaar 8cb1781657 Generate some of the boilerplate for reference implementation specification
PiperOrigin-RevId: 229735735
2019-03-29 15:24:44 -07:00
Alex Zinenko 05b02bb98e TableGen: implement predicate tree and basic simplification
A recent change in TableGen definitions allowed arbitrary AND/OR predicate
compositions at the cost of removing known-true predicate simplification.
Introduce a more advanced simplification mechanism instead.

In particular, instead of folding predicate C++ expressions directly in
TableGen, keep them as is and build a predicate tree in TableGen C++ library.
The predicate expression-substitution mechanism, necessary to implement complex
predicates for nested classes such as `ContainerType`, is replaced by a
dedicated predicate.  This predicate appears in the predicate tree and can be
used for tree matching and separation.  More specifically, subtrees defined
below such predicate may be subject to different transformations than those
that appear above.  For example, a subtree known to be true above the
substitution predicate is not necessarily true below it.

Use the predicate tree structure to eliminate known-true and known-false
predicates before code emission, as well as to collapse AND and OR predicates
if their value can be deduced based on the value of one child.

PiperOrigin-RevId: 229605997
2019-03-29 15:22:58 -07:00
Jacques Pienaar 4b2b5f5267 Enable specifying the op for which the reference implementation should be printed.
Allows emitting reference implementation of multiple ops inside the test lowering pass.

PiperOrigin-RevId: 229603494
2019-03-29 15:22:43 -07:00
Jacques Pienaar a5827fc91d Add attribute matching and transform to pattern rewrites.
Start simple with single predicate match & transform rules for attributes.
* Its unclear whether modelling Attr predicates will be needed so start with allowing matching attributes with a single predicate.
*  The input and output attr type often differs and so add ability to specify a transform between the input and output format.

PiperOrigin-RevId: 229580879
2019-03-29 15:22:14 -07:00
Jacques Pienaar 9d4bb57189 Start a testing pass for EDSC lowering.
This is mostly plumbing to start allowing testing EDSC lowering. Prototype specifying reference implementation using verbose format without any generation/binding support. Add test pass that dumps the constructed EDSC (of which there can only be one). The idea is to enable iterating from multiple sides, this is wrong on many dimensions at the moment.

PiperOrigin-RevId: 229570535
2019-03-29 15:21:44 -07:00
Alex Zinenko bd161ae5bc TableGen: untie Attr from Type
In TableGen definitions, the "Type" class has been used for types of things
that can be stored in Attributes, but not necessarily present in the MLIR type
system.  As a consequence, records like "String" or "DerviedAttrBody" were of
class "Type", which can be confusing.  Furthermore, the "builderCall" field of
the "Type" class serves only for attribute construction.  Some TableGen "Type"
subclasses that correspond to MLIR kinds of types do not have a canonical way
of construction only from the data available in TableGen, e.g. MemRefType would
require the list of affine maps.  This leads to a conclusion that the entities
that describe types of objects appearing in Attributes should be independent of
"Type": they have some properties "Type"s don't and vice versa.

Do not parameterize Tablegen "Attr" class by an instance of "Type".  Instead,
provide a "constBuilderCall" field that can be used to build an attribute from
a constant value stored in TableGen instead of indirectly going through
Attribute.Type.builderCall.  Some attributes still don't have a
"constBuilderCall" because they used to depend on types without a
"builderCall".

Drop definitions of class "Type" that don't correspond to MLIR Types.  Provide
infrastructure to define type-dependent attributes and string-backed attributes
for convenience.

PiperOrigin-RevId: 229570087
2019-03-29 15:21:28 -07:00
Lei Zhang 254821d1db Rename hasCanonicalizationPatterns to hasCanonicalizer
The latter is shorter but still conveys the idea clearly. It is also more
consistent with hasConstantFolder.

PiperOrigin-RevId: 229561774
2019-03-29 15:20:44 -07:00
Alex Zinenko 44e9869f1a TableGen: extract TypeConstraints from Type
MLIR has support for type-polymorphic instructions, i.e. instructions that may
take arguments of different types.  For example, standard arithmetic operands
take scalars, vectors or tensors.  In order to express such instructions in
TableGen, we need to be able to verify that a type object satisfies certain
constraints, but we don't need to construct an instance of this type.  The
existing TableGen definition of Type requires both.  Extract out a
TypeConstraint TableGen class to define restrictions on types.  Define the Type
TableGen class as a subclass of TypeConstraint for consistency.  Accept records
of the TypeConstraint class instead of the Type class as values in the
Arguments class when defining operators.

Replace the predicate logic TableGen class based on conjunctive normal form
with the predicate logic classes allowing for abitrary combinations of
predicates using Boolean operators (AND/OR/NOT).  The combination is
implemented using simple string rewriting of C++ expressions and, therefore,
respects the short-circuit evaluation order.  No logic simplification is
performed at the TableGen level so all expressions must be valid C++.
Maintaining CNF using TableGen only would have been complicated when one needed
to introduce top-level disjunction.  It is also unclear if it could lead to a
significantly simpler emitted C++ code.  In the future, we may replace inplace
predicate string combination with a tree structure that can be simplified in
TableGen's C++ driver.

Combined, these changes allow one to express traits like ArgumentsAreFloatLike
directly in TableGen instead of relying on C++ trait classes.

PiperOrigin-RevId: 229398247
2019-03-29 15:18:23 -07:00