Commit Graph

666 Commits

Author SHA1 Message Date
River Riddle 907403f342 [mlir] Add a new `ConstantLike` trait to better identify operations that represent a "constant".
The current mechanism for identifying is a bit hacky and extremely adhoc, i.e. we explicit check 1-result, 0-operand, no side-effect, and always foldable and then assume that this is a constant. Adding a trait adds structure to this, and makes checking for a constant much more efficient as we can guarantee that all of these things have already been verified.

Differential Revision: https://reviews.llvm.org/D76020
2020-03-12 14:26:15 -07:00
River Riddle 483f82b146 [mlir][SideEffects][NFC] Move the .td definitions for NoSideEffect/RecursiveSideEffect to SideEffects.td
This matches the location of these traits within the source files.

Differential Revision: https://reviews.llvm.org/D75968
2020-03-12 14:26:15 -07:00
River Riddle 320f0b0036 [mlir] Change EffectKind in unsigned for bitfield to avoid miscompile in
MSVC

MSVC has problems if the type of the bitfield is different, leading to
invalid code generation.
2020-03-06 23:01:49 -08:00
River Riddle 20dca52288 [mlir][SideEffects] Enable specifying side effects directly on the arguments/results of an operation.
Summary:
New classes are added to ODS to enable specifying additional information on the arguments and results of an operation. These classes, `Arg` and `Res` allow for adding a description and a set of 'decorators' along with the constraint. This enables specifying the side effects of an operation directly on the arguments and results themselves.

Example:
```
def LoadOp : Std_Op<"load"> {
  let arguments = (ins Arg<AnyMemRef, "the MemRef to load from",
                           [MemRead]>:$memref,
                       Variadic<Index>:$indices);
}
```

Differential Revision: https://reviews.llvm.org/D74440
2020-03-06 14:04:36 -08:00
River Riddle cb1777127c [mlir] Remove successor operands from the Operation class
Summary:
This revision removes all of the functionality related to successor operands on the core Operation class. This greatly simplifies a lot of handling of operands, as well as successors. For example, DialectConversion no longer needs a special "matchAndRewrite" for branching terminator operations.(Note, the existing method was also broken for operations with variadic successors!!)

This also enables terminator operations to define their own relationships with successor arguments, instead of the hardcoded "pass-through" behavior that exists today.

Differential Revision: https://reviews.llvm.org/D75318
2020-03-05 12:53:02 -08:00
River Riddle c98cff5ae4 [mlir] Automatically populate `operand_segment_sizes` in the auto-generated build methods.
This greatly simplifies the requirements for builders using this mechanism for managing variadic operands.

Differential Revision: https://reviews.llvm.org/D75317
2020-03-05 12:52:22 -08:00
River Riddle 01f7431b5b [mlir][DeclarativeParser] Add support for formatting operations with AttrSizedOperandSegments.
This attribute details the segment sizes for operand groups within the operation. This revision add support for automatically populating this attribute in the declarative parser.

Differential Revision: https://reviews.llvm.org/D75315
2020-03-05 12:51:28 -08:00
River Riddle 621d7cca37 [mlir] Add a new BranchOpInterface to allow for opaquely interfacing with branching terminator operations.
This interface contains the necessary components to provide the same builtin behavior that terminators have. This will be used in future revisions to remove many of the hardcoded constraints placed on successors and successor operands. The interface initially contains three methods:

```c++
// Return a set of values corresponding to the operands for successor 'index', or None if the operands do not correspond to materialized values.
Optional<OperandRange> getSuccessorOperands(unsigned index);

// Return true if this terminator can have it's successor operands erased.
bool canEraseSuccessorOperand();

// Erase the operand of a successor. This is only valid to call if 'canEraseSuccessorOperand' returns true.
void eraseSuccessorOperand(unsigned succIdx, unsigned opIdx);
```

Differential Revision: https://reviews.llvm.org/D75314
2020-03-05 12:50:35 -08:00
River Riddle c0fd5e657e [mlir] Add traits for verifying the number of successors and providing relevant accessors.
This allows for simplifying OpDefGen, as well providing specializing accessors for the different successor counts. This mirrors the existing traits for operands and results.

Differential Revision: https://reviews.llvm.org/D75313
2020-03-05 12:49:59 -08:00
Jacques Pienaar 1bedb23407 [mlir][ods] Add query for derived attribute
For ODS generated operations enable querying whether there is a derived
attribute with a given name.

Rollforward of commit 5aa57c2 without using llvm::is_contained.
2020-03-03 12:04:16 -08:00
Stephan Herhut 57b8b2cc50 Revert "[mlir][ods] Add query for derived attribute"
This reverts commit 5aa57c2812.

The source code generated due to this ods change does not compile,
as it passes to few arguments to llvm::is_contained.
2020-03-03 10:23:38 +01:00
Jacques Pienaar 5aa57c2812 [mlir][ods] Add query for derived attribute
For ODS generated operations enable querying whether there is a derived
attribute with a given name.
2020-03-02 13:31:35 -08:00
Jacques Pienaar 4dc39ae752 [mlir] Fix typo 2020-02-28 10:59:52 -08:00
Alex Zinenko 3a1b34ff69 [mlir] Intrinsics generator: use TableGen-defined builder function
Originally, intrinsics generator for the LLVM dialect has been producing
customized code fragments for the translation of MLIR operations to LLVM IR
intrinsics. LLVM dialect ODS now provides a generalized version of the
translation code, parameterizable with the properties of the operation.
Generate ODS that uses this version of the translation code instead of
generating a new version of it for each intrinsic.

Differential Revision: https://reviews.llvm.org/D74893
2020-02-25 11:59:04 +01:00
River Riddle 42060c0a98 [mlir][DeclarativeParser][NFC] Use explicit type names in TypeSwitch to
appease older GCC.

Older versions of GCC are unable to properly capture 'this' in template lambdas,
resulting in errors.
2020-02-21 16:14:13 -08:00
River Riddle 9eb436feaa [mlir][DeclarativeParser] Add support for formatting the successors of an operation.
This revision add support for formatting successor variables in a similar way to operands, attributes, etc.

Differential Revision: https://reviews.llvm.org/D74789
2020-02-21 15:15:32 -08:00
River Riddle b1de971ba8 [mlir][ODS] Add support for specifying the successors of an operation.
This revision add support in ODS for specifying the successors of an operation. Successors are specified via the `successors` list:
```
let successors = (successor AnySuccessor:$target, AnySuccessor:$otherTarget);
```

Differential Revision: https://reviews.llvm.org/D74783
2020-02-21 15:15:32 -08:00
River Riddle ca4ea51c0a [mlir][DeclarativeParser] Add an 'attr-dict-with-keyword' directive
This matches the '(print|parse)OptionalAttrDictWithKeyword' functionality provided by the assembly parser/printer.

Differential Revision: https://reviews.llvm.org/D74682
2020-02-21 15:15:32 -08:00
River Riddle 2d0477a003 [mlir][DeclarativeParser] Add basic support for optional groups in the assembly format.
When operations have optional attributes, or optional operands(i.e. empty variadic operands), the assembly format often has an optional section to represent these arguments. This revision adds basic support for defining an "optional group" in the assembly format to support this. An optional group is defined by wrapping a set of elements in `()` followed by `?` and requires the following:

* The first element of the group must be either a literal or an operand argument.
  - This is because the first element must be optionally parsable.
* There must be exactly one argument variable within the group that is marked as the anchor of the group. The anchor is the element whose presence controls whether the group should be printed/parsed. An element is marked as the anchor by adding a trailing `^`.
* The group must only contain literals, variables, and type directives.
  - Any attribute variables may be used, but only optional attributes can be marked as the anchor.
  - Only variadic, i.e. optional, operand arguments can be used.
  - The elements of a type directive must be defined within the same optional group.

An example of this can be seen with the assembly format for ReturnOp, which has a variadic number of operands.

```
def ReturnOp : ... {
  let arguments = (ins Variadic<AnyType>:$operands);

  // We only print the operands+types if there are a non-zero number
  // of operands.
  let assemblyFormat = "attr-dict ($operands^ `:` type($operands))?";
}
```

Differential Revision: https://reviews.llvm.org/D74681
2020-02-21 15:15:31 -08:00
River Riddle 26222db01b [mlir][DeclarativeParser] Add support for the TypesMatchWith trait.
This allows for injecting type constraints that are not direct 1-1 mappings, for example when one type is equal to the element type of another. This allows for moving over several more parsers to the declarative form.

Differential Revision: https://reviews.llvm.org/D74648
2020-02-21 15:15:31 -08:00
River Riddle c32c8fd143 [mlir] Use getOperation()->setAttr when generating attribute set
methods.

This avoids the need to resolve overloads when the current operation
also defines a 'setAttr' method.
2020-02-20 20:08:33 -08:00
River Riddle 6b6c96695c [mlir][ODS] Add a new trait `TypesMatchWith`
Summary:
This trait takes three arguments: lhs, rhs, transformer. It verifies that the type of 'rhs' matches the type of 'lhs' when the given 'transformer' is applied to 'lhs'. This allows for adding constraints like: "the type of 'a' must match the element type of 'b'". A followup revision will add support in the declarative parser for using these equality constraints to port more c++ parsers to the declarative form.

Differential Revision: https://reviews.llvm.org/D74647
2020-02-19 10:18:58 -08:00
Alexandre Eichenberger 476ca094c8 [mlir][ods] Adding attribute setters generation
In some dialects, attributes may have default values that may be
determined only after shape inference. For example, attributes that
are dependent on the rank of the input cannot be assigned a default
value until the rank of the tensor is inferred.

While we can set attributes without explicit setters, referring to
the attributes via accessors instead of having to use the string
interface is better for compile time verification.

The proposed patch add one method per operation attribute that let us
set its value. The code is a very small modification of the existing
getter methods.

Differential Revision: https://reviews.llvm.org/D74143
2020-02-19 11:49:34 -05:00
Tamas Berghammer 066a76a234 Support OptionalAttr inside a StructAttr
Differential revision: https://reviews.llvm.org/D74768
2020-02-19 12:47:04 +00:00
riverriddle@google.com 857b655d7a [mlir] Allow adding extra class declarations to interfaces.
Summary: This matches the similar feature on operation definitions.

Reviewers: jpienaar, antiagainst

Reviewed By: jpienaar, antiagainst

Subscribers: mehdi_amini, burmako, shauheen, antiagainst, nicolasvasilache, arpith-jacob, mgester, lucyrfox, liufengdb, Joonsoo, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D74438
2020-02-15 23:54:42 -08:00
River Riddle 5756bc4382 [mlir][DeclarativeParser] Add support for formatting enum attributes in the string form.
Summary: This revision adds support to the declarative parser for formatting enum attributes in the symbolized form. It uses this new functionality to port several of the SPIRV parsers over to the declarative form.

Differential Revision: https://reviews.llvm.org/D74525
2020-02-13 17:11:48 -08:00
River Riddle a134ccbbeb [mlir][DeclarativeParser] Move operand type resolution into a functor to
share code.

This reduces the duplication for the two different cases.
2020-02-12 23:56:07 -08:00
River Riddle 1b2c16f2ae [mlir][DeclarativeParser] Add support for attributes with buildable types.
This revision adds support in the declarative assembly form for printing attributes with buildable types without the type, and moves several more parsers over to the declarative form.

Differential Revision: https://reviews.llvm.org/D74276
2020-02-08 15:46:46 -08:00
River Riddle abe6d1174d [mlir] Emit a fatal error when the assembly format is invalid
This revision makes sure that errors emitted outside of testing are treated as fatal errors. This avoids the current silent failures that occur when the format is invalid.
2020-02-03 22:14:33 -08:00
River Riddle fbba639517 [mlir][ODS] Refactor BuildableType to use $_builder as part of the format
Summary:
Currently BuildableType is assumed to be preceded by a builder. This prevents constructing types that don't have a callable 'get' method with the builder. This revision reworks the format to be like attribute builders, i.e. by accepting $_builder within the format itself.

Differential Revision: https://reviews.llvm.org/D73736
2020-02-03 21:55:34 -08:00
River Riddle 7ef37a5f99 [mlir] Initial support for type constraints in the declarative assembly format
Summary: This revision add support for accepting a few type constraints, e.g. AllTypesMatch, when inferring types for operands and results. This is used to remove the c++ parsers for several additional operations.

Differential Revision: https://reviews.llvm.org/D73735
2020-02-03 21:55:09 -08:00
Alex Zinenko eb67bd78dc [mlir] LLVM dialect: Generate conversions between EnumAttrCase and LLVM API
Summary:
MLIR materializes various enumeration-based LLVM IR operands as enumeration
attributes using ODS. This requires bidirectional conversion between different
but very similar enums, currently hardcoded. Extend the ODS modeling of
LLVM-specific enumeration attributes to include the name of the corresponding
enum in the LLVM C++ API as well as the names of specific enumerants. Use this
new information to automatically generate the conversion functions between enum
attributes and LLVM API enums in the two-way conversion between the LLVM
dialect and LLVM IR proper.

Differential Revision: https://reviews.llvm.org/D73468
2020-01-30 21:54:56 +01:00
River Riddle 1c158d0f90 [mlir] Add support for generating the parser/printer from the declarative operation format.
Summary:
This revision add support, and testing, for generating the parser and printer from the declarative operation format.

Differential Revision: https://reviews.llvm.org/D73406
2020-01-30 11:43:40 -08:00
River Riddle b3a1d09c1c [mlir] Add initial support for parsing a declarative operation assembly format
Summary:
This is the first revision in a series that adds support for declaratively specifying the asm format of an operation. This revision
focuses solely on parsing the format. Future revisions will add support for generating the proper parser/printer, as well as
transitioning the syntax definition of many existing operations.

This was originally proposed here:
https://llvm.discourse.group/t/rfc-declarative-op-assembly-format/340

Differential Revision: https://reviews.llvm.org/D73405
2020-01-30 11:43:40 -08:00
Alex Zinenko fdc496a3d3 [mlir] EnumsGen: dissociate string form of integer enum from C++ symbol name
Summary:
In some cases, one may want to use different names for C++ symbol of an
enumerand from its string representation. In particular, in the LLVM dialect
for, e.g., Linkage, we would like to preserve the same enumerand names as LLVM
API and the same textual IR form as LLVM IR, yet the two are different
(CamelCase vs snake_case with additional limitations on not being a C++
keyword).

Modify EnumAttrCaseInfo in OpBase.td to include both the integer value and its
string representation. By default, this representation is the same as C++
symbol name. Introduce new IntStrAttrCaseBase that allows one to use different
names. Exercise it for LLVM Dialect Linkage attribute. Other attributes will
follow as separate changes.

Differential Revision: https://reviews.llvm.org/D73362
2020-01-30 17:04:00 +01:00
Benjamin Kramer adcd026838 Make llvm::StringRef to std::string conversions explicit.
This is how it should've been and brings it more in line with
std::string_view. There should be no functional change here.

This is mostly mechanical from a custom clang-tidy check, with a lot of
manual fixups. It uncovers a lot of minor inefficiencies.

This doesn't actually modify StringRef yet, I'll do that in a follow-up.
2020-01-28 23:25:25 +01:00
Mehdi Amini 308571074c Mass update the MLIR license header to mention "Part of the LLVM project"
This is an artifact from merging MLIR into LLVM, the file headers are
now aligned with the rest of the project.
2020-01-26 03:58:30 +00:00
Alex Zinenko b901335193 [mlir] Use all_of instead of a manual loop in IntrinsicGen. NFC
This was suggested in post-commit review of D72926.
2020-01-24 11:29:35 +01:00
Marcello Maggioni be9f09c768 [mlir] Add option to use custom base class for dialect in LLVMIRIntrinsicGen.
Summary:
LLVMIRIntrinsicGen is using LLVM_Op as the base class for intrinsics.
This works for LLVM intrinsics in the LLVM Dialect, but when we are
trying to convert custom intrinsics that originate from a custom
LLVM dialect (like NVVM or ROCDL) these usually have a different
"cppNamespace" that needs to be applied to these dialect.

These dialect specific characteristics (like "cppNamespace")
are typically organized by creating a custom op (like NVVM_Op or
ROCDL_Op) that passes the correct dialect to the LLVM_OpBase class.

It seems natural to allow LLVMIRIntrinsicGen to take that into
consideration when generating the conversion code from one of these
dialect to a set of target specific intrinsics.

Reviewers: rriddle, andydavis1, antiagainst, nicolasvasilache, ftynse

Subscribers: jdoerfert, mehdi_amini, jpienaar, burmako, shauheen, arpith-jacob, mgester, lucyrfox, aartbik, liufengdb, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D73233
2020-01-23 11:23:25 -08:00
Marcello Maggioni 04a151710e [mlir] Swap use of to_vector() with lookupValues() in LLVMIRIntrinsicGen
Summary:
llvm::to_vector() accepts a Range value and not the pair of arguments
we are currently passing. Also we probably want the lowered LLVM
values in the vector, while operand_begin()/operand_end() on MLIR ops
returns MLIR types. lookupValues() seems the correct way to collect
such values.

Reviewers: rriddle, andydavis1, antiagainst, nicolasvasilache, ftynse

Subscribers: jdoerfert, mehdi_amini, jpienaar, burmako, shauheen, arpith-jacob, mgester, lucyrfox, liufengdb, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D73137
2020-01-22 07:56:24 -08:00
Jacques Pienaar 178562fb35 [mlir] Enable specifying verify on OpInterface
Summary:
Add method in ODS to specify verification for operations implementing a
OpInterface. Use this with infer type op interface to verify that the
inferred type matches the return type and remove special case in
TestPatterns.

This could also have been achieved by using OpInterfaceMethod but verify
seems pretty common and it is not an arbitrary method that just happened
to be named verifyTrait, so having it be defined in special way seems
appropriate/better documenting.

Differential Revision: https://reviews.llvm.org/D73122
2020-01-22 04:43:22 -08:00
Marcello Maggioni cbf08d0f57 [mlir] Fix LLVM intrinsic convesion generator for overloadable types.
Summary:
If an intrinsic has overloadable types like llvm_anyint_ty or
llvm_anyfloat_ty then to getDeclaration() we need to pass a list
of the types that are "undefined" essentially concretizing them.

This patch add support for deriving such types from the MLIR op
that has been matched.

Reviewers: andydavis1, ftynse, nicolasvasilache, antiagainst

Subscribers: mehdi_amini, rriddle, jpienaar, burmako, shauheen, arpith-jacob, mgester, lucyrfox, liufengdb, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D72974
2020-01-21 11:52:30 -08:00
Lei Zhang f2dc179d68 [mlir][ods] Fix StringRef initialization in builders
For the generated builder taking in unwrapped attribute values,
if the argument is a string, we should avoid wrapping it in quotes;
otherwise we are always setting the string attribute to contain
the string argument's name. The quotes come from StrinAttr's
`constBuilderCall`, which is reasonable for string literals, but
not function arguments containing strings.

Differential Revision: https://reviews.llvm.org/D72977
2020-01-21 14:12:27 -05:00
Jacques Pienaar b70e4efb75 [mlir] Generalize broadcastable trait operands
Summary:
Generalize broadcastable trait to variadic operands. Update the
documentation that still talked about element type as part of
broadcastable trait (that bug was already fixed). Also rename
Broadcastable to ResultBroadcastableShape to be more explicit that the
trait affects the result shape (it is possible for op to allow
broadcastable operands but not have result shape that is broadcast
compatible with operands).

Doing some intermediate work to have getBroadcastedType take an optional
elementType as input and use that if specified, instead of the common
element type of type1 and type2 in this function.

Differential Revision: https://reviews.llvm.org/D72559
2020-01-20 13:02:14 -08:00
Kazuaki Ishizaki fc817b09e2 [mlir] NFC: Fix trivial typos in comments
Differential Revision: https://reviews.llvm.org/D73012
2020-01-20 03:17:03 +00:00
Lei Zhang f35b5a7297 [mlir][spirv] Explicitly construct ArrayRef from array
Hopefully this pleases GCC 5.
2020-01-17 13:44:37 -05:00
Lei Zhang 859e379ffb [mlir][spirv] Explicitly set the size of static arrays 2020-01-17 12:33:05 -05:00
Alex Zinenko f343544b81 [mlir] Generator converting LLVM intrinsics defs to MLIR ODS
Introduce a new generator for MLIR tablegen driver that consumes LLVM IR
intrinsic definitions and produces MLIR ODS definitions. This is useful to
bulk-generate MLIR operations equivalent to existing LLVM IR intrinsics, such
as additional arithmetic instructions or NVVM.

A test exercising the generation is also added. It reads the main LLVM
intrinsics file and produces ODS to make sure the TableGen model remains in
sync with what is used in LLVM.

Differential Revision: https://reviews.llvm.org/D72926
2020-01-17 18:20:24 +01:00
Lei Zhang 8bcf976841 [mlir][spirv] Add `const` qualifier for static arrays
This makes the local variable `implies` to have the correct
type to satisfy ArrayRef's constructor:

  /*implicit*/ constexpr ArrayRef(const T (&Arr)[N])

Hopefully this should please GCC 5.

Differential Revision: https://reviews.llvm.org/D72924
2020-01-17 11:45:41 -05:00
Lei Zhang 267483ac70 [mlir][spirv] Support implied extensions and capabilities
In SPIR-V, when a new version is introduced, it is possible some
existing extensions will be incorporated into it so that it becomes
implicitly declared if targeting the new version. This affects
conversion target specification because we need to take this into
account when allowing what extensions to use.

For a capability, it may also implies some other capabilities,
for example, the `Shader` capability implies `Matrix` the capability.
This should also be taken into consideration when preparing the
conversion target: when we specify an capability is allowed, all
its recursively implied capabilities are also allowed.

This commit adds utility functions to query implied extensions for
a given version and implied capabilities for a given capability
and updated SPIRVConversionTarget to use them.

This commit also fixes a bug in availability spec. When a symbol
(op or enum case) can be enabled by an extension, we should drop
it's minimal version requirement. Being enabled by an extension
naturally means the symbol can be used by *any* SPIR-V version
as long as the extension is supported. The grammar still encodes
the 'version' field for such cases, but it should be interpreted
as a different way: rather than meaning a minimal version
requirement, it says the symbol becomes core at that specific
version.

Differential Revision: https://reviews.llvm.org/D72765
2020-01-17 08:01:57 -05:00
Lei Zhang 37dfc64687 Revert "[mlir][ods] Support dialect specific content emission via hooks"
This reverts commit 397215cc30 because
this feature needs more discussion.
2020-01-17 07:56:21 -05:00
Kazuaki Ishizaki 73f371c31d [mlir] NFC: Fix trivial typos
Summary: Fix trivial typos

Differential Revision: https://reviews.llvm.org/D72672
2020-01-16 23:58:58 +01:00
Jacques Pienaar fa26a37d36 [mlir] Add shaped container component type interface
Summary:
* Add shaped container type interface which allows infering the shape, element
  type and attribute of shaped container type separately. Show usage by way of
  tensor type inference trait which combines the shape & element type in
  infering a tensor type;
  - All components need not be specified;
  - Attribute is added to allow for layout attribute that was previously
    discussed;
* Expand the test driver to make it easier to test new creation instances
  (adding new operands or ops with attributes or regions would trigger build
  functions/type inference methods);
  - The verification part will be moved out of the test and to verify method
    instead of ops implementing the type inference interface in a follow up;
* Add MLIRContext as arg to possible to create type for ops without arguments,
  region or location;
* Also move out the section in OpDefinitions doc to separate ShapeInference doc
  where the shape function requirements can be captured;
  - Part of this would move to the shape dialect and/or shape dialect ops be
    included as subsection of this doc;
* Update ODS's variable usage to match camelBack format for builder,
  state and arg variables;
  - I could have split this out, but I had to make some changes around
    these and the inconsistency bugged me :)

Differential Revision: https://reviews.llvm.org/D72432
2020-01-15 13:28:39 -08:00
River Riddle 2bdf33cc4c [mlir] NFC: Remove Value::operator* and Value::operator-> now that Value is properly value-typed.
Summary: These were temporary methods used to simplify the transition.

Reviewed By: antiagainst

Differential Revision: https://reviews.llvm.org/D72548
2020-01-11 08:54:39 -08:00
Lei Zhang 397215cc30 [mlir][ods] Support dialect specific content emission via hooks
Thus far we can only generate the same set of methods even for
operations in different dialects. This is problematic for dialects that
want to generate additional operation class methods programmatically,
e.g., a special builder method or attribute getter method. Apparently
we cannot update the OpDefinitionsGen backend every time when such
a need arises. So this CL introduces a hook into the OpDefinitionsGen
backend to allow dialects to emit additional methods and traits to
operation classes.

Differential Revision: https://reviews.llvm.org/D72514
2020-01-10 18:39:28 -05:00
Lei Zhang ca4a55fabb [mlir] NFC: put C++ code emission classes in their own files
This exposes thse classes so that they can be used in interfaces.

Differential Revision: https://reviews.llvm.org/D72514
2020-01-10 18:38:59 -05:00
Alexandre Ganea e19188af0a [mlir] Compilation fix: use LLVM_ATTRIBUTE_UNUSED following 6656e961c0
Differential Revision: https://reviews.llvm.org/D72124
2020-01-03 16:31:33 -05:00
Lei Zhang 5d5d5838ce [mlir] Enhance classof() checks in StructsGen
Previously we only check that each field is of the correct
mlir::Attribute subclass. This commit enhances to also consider
the attribute's types, by leveraging the constraints already
encoded in TableGen attribute definitions.

Reviewed By: rsuderman

Differential Revision: https://reviews.llvm.org/D72162
2020-01-03 15:13:16 -05:00
Jacques Pienaar 8f1caf518f [mlir] Only generate default for uncovered cases
Have to explicitly check if all cases are covered instead.
2020-01-02 12:55:14 -08:00
Jacques Pienaar f533fa3af5 [mlir] Revert default case that was needed
This one isn't always complete.
2020-01-02 12:32:41 -08:00
Jacques Pienaar 3d83d8259c [mlir] Remove redudant default cases
These provide no value and trigger -Wcovered-switch-default.
2020-01-02 12:24:42 -08:00
Nicolas Vasilache 2140a973f2 [mlir][Linalg] Extend generic ops to allow tensors
Summary:
    This diff adds support to allow `linalg.generic` and
    `linalg.indexed_generic` to take tensor input and output
    arguments.

    The subset of output tensor operand types must appear
    verbatim in the result types after an arrow. The parser,
    printer and verifier are extended to accomodate this
    behavior.

    The Linalg operations now support variadic ranked tensor
    return values. This extension exhibited issues with the
    current handling of NativeCall in RewriterGen.cpp. As a
    consequence, an explicit cast to `SmallVector<Value, 4>`
    is added in the proper place to support the new behavior
    (better suggestions are welcome).

    Relevant cleanups and name uniformization are applied.

    Relevant invalid and roundtrip test are added.

    Reviewers: mehdi_amini, rriddle, jpienaar, antiagainst, ftynse

    Subscribers: burmako, shauheen, llvm-commits

    Tags: #llvm

    Differential Revision: https://reviews.llvm.org/D72022
2020-01-02 13:54:57 -05:00
Lei Zhang a81cb1b8bf [mlir][spirv] Allow specifying availability on enum attribute cases
Lots of SPIR-V ops take enum attributes and certain enum cases
need extra capabilities or extensions to be available. This commit
extends to allow specifying availability spec on enum cases.
Extra utility functions are generated for the corresponding enum
classes to return the availability requirement. The availability
interface implemention for a SPIR-V op now goes over all enum
attributes to collect the availability requirements.

Reviewed By: mravishankar

Differential Revision: https://reviews.llvm.org/D71947
2020-01-02 13:19:44 -05:00
Fangrui Song eeef50b1fe [mlir] Fix -Wrange-loo-analysis warnings
for (const auto &x : llvm::zip(..., ...))

->

for (auto x : llvm::zip(..., ...))

The return type of zip() is a wrapper that wraps a tuple of references.

> warning: loop variable 'p' is always a copy because the range of type 'detail::zippy<detail::zip_shortest, ArrayRef<long> &, ArrayRef<long> &>' does not return a reference [-Wrange-loop-analysis]
2020-01-01 16:06:04 -08:00
Alexandre Ganea 6656e961c0 [mlir] Fix compilation warnings
Fixes:
- (MSVC) F:\llvm-project\mlir\lib\Dialect\Linalg\Analysis\DependenceAnalysis.cpp(103): warning C4551: function call missing argument list
- (Clang) tools\mlir\lib\Dialect\SPIRV\SPIRVCanonicalization.inc(232,1): warning: unused function 'populateWithGenerated' [-Wunused-function]
2020-01-01 17:29:04 -05:00
Lei Zhang b30d87a90b [mlir][spirv] Add basic definitions for supporting availability
SPIR-V has a few mechanisms to control op availability: version,
extension, and capabilities. These mechanisms are considered as
different availability classes.

This commit introduces basic definitions for modelling SPIR-V
availability classes. Specifically, an `Availability` class is
added to SPIRVBase.td, along with two subclasses: MinVersion
and MaxVersion for versioning. SPV_Op is extended to take a
list of `Availability`. Each `Availability` instance carries
information for generating op interfaces for the corresponding
availability class and also the concrete availability
requirements.

With the availability spec on ops, we can now auto-generate the
op interfaces of all SPIR-V availability classes and also
synthesize the op's implementations of these interfaces. The
interface generation is done via new TableGen backends
-gen-avail-interface-{decls|defs}. The op's implementation is
done via -gen-spirv-avail-impls.

Differential Revision: https://reviews.llvm.org/D71930
2019-12-27 16:25:09 -05:00
Eric Christopher 371038e3ff Add an __attribute__((unused)) to populateWithGenerated since it might
not be used where defined and is autogenerated.
2019-12-26 18:48:59 -08:00
River Riddle e62a69561f NFC: Replace ValuePtr with Value and remove it now that Value is value-typed.
ValuePtr was a temporary typedef during the transition to a value-typed Value.

PiperOrigin-RevId: 286945714
2019-12-23 16:36:53 -08:00
Mehdi Amini 56222a0694 Adjust License.txt file to use the LLVM license
PiperOrigin-RevId: 286906740
2019-12-23 15:33:37 -08:00
River Riddle 35807bc4c5 NFC: Introduce new ValuePtr/ValueRef typedefs to simplify the transition to Value being value-typed.
This is an initial step to refactoring the representation of OpResult as proposed in: https://groups.google.com/a/tensorflow.org/g/mlir/c/XXzzKhqqF_0/m/v6bKb08WCgAJ

This change will make it much simpler to incrementally transition all of the existing code to use value-typed semantics.

PiperOrigin-RevId: 286844725
2019-12-22 22:00:23 -08:00
River Riddle 29807ff5e4 Add support for providing a default implementation for an interface method.
This enables providing a default implementation of an interface method. This method is defined on the Trait that is attached to the operation, and thus has all of the same constraints and properties as any other interface method. This allows for interface authors to provide a conservative default implementation for certain methods, without requiring that all users explicitly define it. The default implementation can be specified via the argument directly after the interface method body:

  StaticInterfaceMethod<
    /*desc=*/"Returns whether two array of types are compatible result types for an op.",
    /*retTy=*/"bool",
    /*methodName=*/"isCompatibleReturnTypes",
    /*args=*/(ins "ArrayRef<Type>":$lhs, "ArrayRef<Type>":$rhs),
    /*methodBody=*/[{
      return ConcreteOp::isCompatibleReturnTypes(lhs, rhs);
    }],
    /*defaultImplementation=*/[{
      /// Returns whether two arrays are equal as strongest check for
      /// compatibility by default.
      return lhs == rhs;
    }]

PiperOrigin-RevId: 286226054
2019-12-18 11:09:11 -08:00
Mahesh Ravishankar a0557ea9d6 Fix (de)serialization generation for SPV_ScopeAttr, SPV_MemorySemanticsAttr.
Scope and Memory Semantics attributes need to be serialized as a
constant integer value and the <id> needs to be used to specify the
value. Fix the auto-generated SPIR-V (de)serialization to handle this.

PiperOrigin-RevId: 285849431
2019-12-16 14:23:08 -08:00
Mehdi Amini c290e993b2 Remove unused variable (fix warning) NFC
PiperOrigin-RevId: 285799680
2019-12-16 10:28:44 -08:00
Jing Pu 27ae92516b Skip generating C++ for "DeclareOpInterfaceMethods" in op interface gen.
This is needed for calling the generator on a .td file that contains both OpInterface definitions and op definitions with DeclareOpInterfaceMethods<...> Traits.

PiperOrigin-RevId: 285465784
2019-12-13 17:08:33 -08:00
Jacques Pienaar a50cb184a0 Fix logic on when to emit collective type but separate arg builder
Got the comment right but the code wrong :/

PiperOrigin-RevId: 285270561
2019-12-12 14:23:14 -08:00
Jacques Pienaar 41a73ddce8 Add type inference variant for separate params builder generated
Add variant that does invoke infer type op interface where defined. Also add entry function that invokes that different separate argument builders for wrapped, unwrapped and inference variant.

PiperOrigin-RevId: 285220709
2019-12-12 10:36:14 -08:00
Jacques Pienaar 89cef725f4 ODS: Generate named accessors for raw attributes
Currently named accessors are generated for attributes returning a consumer
friendly type. But sometimes the attributes are used while transforming an
existing op and then the returned type has to be converted back into an
attribute or the raw `getAttr` needs to be used. Generate raw named accessor
for attributes to reference the raw attributes without having to use the string
interface for better compile time verification. This allows calling
`blahAttr()` instead of `getAttr("blah")`.

Raw here refers to returning the underlying storage attribute.

PiperOrigin-RevId: 284583426
2019-12-09 10:29:34 -08:00
Kazuaki Ishizaki ae05cf27c6 Minor spelling tweaks
Closes tensorflow/mlir#304

PiperOrigin-RevId: 284568358
2019-12-09 09:23:48 -08:00
River Riddle d6ee6a0310 Update the builder API to take ValueRange instead of ArrayRef<Value *>
This allows for users to provide operand_range and result_range in builder.create<> calls, instead of requiring an explicit copy into a separate data structure like SmallVector/std::vector.

PiperOrigin-RevId: 284360710
2019-12-07 10:35:41 -08:00
Jacques Pienaar 4add9edd72 Change inferReturnTypes to return LogicalResult and values
Previously the error case was using a sentinel in the error case which was bad. Also make the one `build` invoke the other `build` to reuse verification there.

And follow up on suggestion to use formatv which I missed during previous review.

PiperOrigin-RevId: 284265762
2019-12-06 14:42:45 -08:00
Jacques Pienaar 398f04aa49 Generate builder for ops that use InferTypeOpInterface trait in ODS
For ops with infer type op interface defined, generate version that calls the inferal method on build. This is intermediate step to removing special casing of SameOperandsAndResultType & FirstAttrDereivedResultType. After that would be generating the inference code, with the initial focus on shaped container types. In between I plan to refactor these a bit to reuse generated paths. The intention would not be to add the type inference trait in multiple places, but rather to take advantage of the current modelling in ODS where possible to emit it instead.

Switch the `inferReturnTypes` method to be static.

Skipping ops with regions here as I don't like the Region vs unique_ptr<Region> difference at the moment, and I want the infer return type trait to be useful for verification too. So instead, just skip it for now to avoid churn.

PiperOrigin-RevId: 284217913
2019-12-06 10:53:06 -08:00
Kazuaki Ishizaki 84a6182ddd minor spelling tweaks
Closes tensorflow/mlir#290

COPYBARA_INTEGRATE_REVIEW=https://github.com/tensorflow/mlir/pull/290 from kiszk:spelling_tweaks_201912 9d9afd16a723dd65754a04698b3976f150a6054a
PiperOrigin-RevId: 284169681
2019-12-06 05:59:30 -08:00
Lei Zhang 364b92fa10 NFC: use `&&` instead of `and`
PiperOrigin-RevId: 283392575
2019-12-02 12:27:14 -08:00
Lei Zhang b41162b3af [ODS] Generate builders taking unwrapped value and defaults for attributes
Existing builders generated by ODS require attributes to be passed
in as mlir::Attribute or its subclasses. This is okay foraggregate-
parameter builders, which is primarily to be used by programmatic
C++ code generation; it is inconvenient for separate-parameter
builders meant to be called in manually written C++ code because
it requires developers to wrap raw values into mlir::Attribute by
themselves.

This CL extends to generate additional builder methods that
take raw values for attributes and handles the wrapping in the
builder implementation. Additionally, if an attribute appears
late in the arguments list and has a default value, the default
value is supplied in the declaration if possible.

PiperOrigin-RevId: 283355919
2019-12-02 09:33:57 -08:00
Lei Zhang 4982eaf87c [DRR] Introduce `$_` to ignore op argument match
Right now op argument matching in DRR is position-based, meaning we need to
specify N arguments for an op with N ODS-declared argument. This can be annoying
when we don't want to capture all the arguments. `$_` is to remedy the situation.

PiperOrigin-RevId: 283339992
2019-12-02 07:54:50 -08:00
Jacques Pienaar 2235333d58 mlir-tblgen: Dump input records when no generator is set
Follow LLVM's tblgen convention when no generator is set instead of asserting.

PiperOrigin-RevId: 283073690
2019-11-29 10:43:58 -08:00
Lei Zhang 13c6e419ca Add support for AttrSizedOperandSegments/AttrSizedResultSegments
Certain operations can have multiple variadic operands and their size
relationship is not always known statically. For such cases, we need
a per-op-instance specification to divide the operands into logical
groups or segments. This can be modeled by attributes.

This CL introduces C++ trait AttrSizedOperandSegments for operands and
AttrSizedResultSegments for results. The C++ trait just guarantees
such size attribute has the correct type (1D vector) and values
(non-negative), etc. It serves as the basis for ODS sugaring that
with ODS argument declarations we can further verify the number of
elements match the number of ODS-declared operands and we can generate
handy getter methods.

PiperOrigin-RevId: 282467075
2019-11-25 17:26:50 -08:00
River Riddle c35378003c Add support for using the ODS result names as the Asm result names for multi-result operations.
This changes changes the OpDefinitionsGen to automatically add the OpAsmOpInterface for operations with multiple result groups using the provided ODS names. We currently just limit the generation to multi-result ops as most single result operations don't have an interesting name(result/output/etc.). An example is shown below:
// The following operation:
def MyOp : ... {
  let results = (outs AnyType:$first, Variadic<AnyType>:$middle, AnyType);
}

// May now be printed as:
%first, %middle:2, %0 = "my.op" ...

PiperOrigin-RevId: 281834156
2019-11-21 14:55:46 -08:00
Lei Zhang 88843ae37c Use aggregate-parameter builder for ops having autogen type-deduction builder
Thus far DRR always invokes the separate-parameter builder (i.e., requiring
a separate parameter for each result-type/operand/attribute) for creating
ops, no matter whether we can auto-generate a builder with type-deduction
ability or not.

This CL changes the path for ops that we can auto-generate type-deduction
builders, i.e., with SameOperandsAndResultType/FirstAttrDerivedResultType
traits. Now they are going through a aggregate-parameter builder (i.e.,
requiring one parameter for all result-types/operands/attributes).
attributes.)

It is expected this approach will be more friendly for future shape inference
function autogen and calling those autogen'd shape inference function without
excessive packing and repacking operand/attribute lists.
Also, it would enable better support for creating ops with optional attributes
because we are not required to provide an Attribute() as placeholder for
an optional attribute anymore.

PiperOrigin-RevId: 280654800
2019-11-15 07:33:54 -08:00
Hanhan Wang 85d7fb3324 Make VariableOp instructions be in the first block in the function.
Since VariableOp is serialized during processBlock, we add two more fields,
`functionHeader` and `functionBody`, to collect instructions for a function.
After all the blocks have been processed, we append them to the `functions`.

Also, fix a bug in processGlobalVariableOp. The global variables should be
encoded into `typesGlobalValues`.

PiperOrigin-RevId: 280105366
2019-11-12 18:59:15 -08:00
Lei Zhang f4aca03232 [spirv] Properly return when finding error in serialization
PiperOrigin-RevId: 280001339
2019-11-12 10:45:13 -08:00
Lei Zhang 6d2432561c Emit empty lines after headers when generating op docs
This makes the generated doc easier to read and it is also
more friendly to certain markdown parsers like kramdown.

Fixes tensorflow/mlir#221

PiperOrigin-RevId: 278643469
2019-11-05 09:32:17 -08:00
Lei Zhang 2fa865719b Move BitEnumAttr from SPIRVBase.td to OpBase.td
BitEnumAttr is a mechanism for modelling attributes whose value is
a bitfield. It should not be scoped to the SPIR-V dialect and can
be used by other dialects too.

This CL is mostly shuffling code around and adding tests and docs.
Functionality changes are:

* Fixed to use `getZExtValue()` instead of `getSExtValue()` when
  getting the value from the underlying IntegerAttr for a case.
* Changed to auto-detect whether there is a case whose value is
  all bits unset (i.e., zero). If so handle it specially in all
  helper methods.

PiperOrigin-RevId: 277964926
2019-11-01 11:18:19 -07:00
MLIR Team 5e932afd5b Add "[TOC]" to generated documentation
PiperOrigin-RevId: 277354482
2019-10-29 13:39:00 -07:00
Lei Zhang 020f9eb68c [DRR] Allow interleaved operands and attributes
Previously DRR assumes attributes to appear after operands. This was the
previous requirements on ODS, but that has changed some time ago. Fix
DRR to also support interleaved operands and attributes.

PiperOrigin-RevId: 275983485
2019-10-21 20:48:17 -07:00
Lei Zhang aad15d812e [DRR] Address GCC warning by wrapping for statement body with {}
Otherwise, we'll see the following warning when compiling with GCC 8:

warning: this ?for? clause does not guard... [-Wmisleading-indentation]
PiperOrigin-RevId: 275735925
2019-10-20 12:24:07 -07:00
Lei Zhang c5b9fefddc NFC: Rename SPIR-V serializer find*ID() to get*ID() to be consistent
We use get*() in deserizer and other places across the codebase.

PiperOrigin-RevId: 275582390
2019-10-18 18:16:05 -07:00
Lei Zhang 3aae473658 [DRR] Use eraseOp() to replace no-result ops
PiperOrigin-RevId: 275475229
2019-10-18 08:20:25 -07:00
Lei Zhang 603117b2d6 Fix RewriterGen to support using NativeCodeCall as auxiliary pattern
NativeCodeCall is handled differently than normal op creation in RewriterGen
(because its flexibility). It will only be materialized to output stream if
it is used. But when using it for auxiliary patterns, we still want the side
effect even if it is not replacing matched root op's results.

PiperOrigin-RevId: 275265467
2019-10-17 08:39:59 -07:00
Lei Zhang 1358df19ca Add LLVM_DEBUG in RewritersGen.cpp and Pattern.cpp
It's usually hard to understand what went wrong if mlir-tblgen
crashes on some input. This CL adds a few useful LLVM_DEBUG
statements so that we can use mlir-tblegn -debug to figure
out the culprit for a crash.

PiperOrigin-RevId: 275253532
2019-10-17 07:26:22 -07:00
Kazuaki Ishizaki 27f400c813 minor spelling tweaks
--
f93661f2c25aab6cc5bf439606b0a1312998a575 by Kazuaki Ishizaki <ishizaki@jp.ibm.com>:

address @River707's comment

Closes tensorflow/mlir#176

COPYBARA_INTEGRATE_REVIEW=https://github.com/tensorflow/mlir/pull/176 from kiszk:spelling_tweaks_include_tools f93661f2c25aab6cc5bf439606b0a1312998a575
PiperOrigin-RevId: 273830689
2019-10-09 15:07:25 -07:00
Jacques Pienaar 27e8efedf8 Add DialectType and generate docs for dialect types
Add new `typeDescription` (description was already used by base constraint class) field to type to allow writing longer descriptions about a type being defined. This allows for providing additional information/rationale for a defined type. This currently uses `description` as the heading/name for the type in the generated documentation.

PiperOrigin-RevId: 273299332
2019-10-07 08:41:13 -07:00
Jacques Pienaar 77672c9777 Enable emitting dialect summary & description during op generation
Sort ops per dialect and emit summary & description (if provided) of each dialect before emitting the ops of the dialect.

PiperOrigin-RevId: 273077138
2019-10-05 12:21:51 -07:00
Christian Sigg 85dcaf19c7 Fix typos, NFC.
PiperOrigin-RevId: 272851237
2019-10-04 04:37:53 -07:00
MLIR Team 66bcd05bb7 Fold away reduction over 0 dimensions.
PiperOrigin-RevId: 272113564
2019-09-30 18:44:46 -07:00
Jacques Pienaar 0b81eb928b Enable autogenerating OpInterface method declarations
Add DeclareOpInterfaceFunctions to enable specifying whether OpInterfaceMethods
for an OpInterface should be generated automatically. This avoids needing to
declare the extra methods, while also allowing adding function declaration by way of trait/inheritance.

Most of this change is mechanical/extracting classes to be reusable.

PiperOrigin-RevId: 272042739
2019-09-30 12:42:58 -07:00
Jacques Pienaar 19841775d4 Make result ops generated output deterministic
Sort the result ops reported in lexographical order.

PiperOrigin-RevId: 271426258
2019-09-26 14:00:59 -07:00
Lei Zhang 94298cea93 Remove unused variables and methods to address compiler warnings
PiperOrigin-RevId: 271256784
2019-09-25 19:05:30 -07:00
Mahesh Ravishankar 3a4bee0fe1 Miscellaneous fixes to SPIR-V Deserializer (details below).
1) Process and ignore the following debug instructions: OpSource,
OpSourceContinued, OpSourceExtension, OpString, OpModuleProcessed.
2) While processing OpTypeInt instruction, ignore the signedness
specification. Currently MLIR doesnt make a distinction between signed
and unsigned integer types.
3) Process and ignore BufferBlock decoration (similar to Buffer
decoration). StructType needs to be enhanced to track this attribute
since its needed for proper validation checks.
4) Report better error for unhandled instruction during
deserialization.

PiperOrigin-RevId: 271057060
2019-09-24 22:51:02 -07:00
River Riddle 635544fc12 Allow attaching descriptions to OpInterfaces and InterfaceMethods.
This change adds support for documenting interfaces and their methods. A tablegen generator for the interface documentation is also added(gen-op-interface-doc).

Documentation is added to an OpInterface via the `description` field:
def MyOpInterface : OpInterface<"MyOpInterface"> {
  let description = [{
    My interface is very interesting.
  }];
}

Documentation is added to an InterfaceMethod via a new `description` field that comes right before the optional body:

InterfaceMethod<"void", "foo", (ins), [{
  This is the foo method.
}]>,

PiperOrigin-RevId: 270965485
2019-09-24 12:46:17 -07:00
Denis Khalikov 2ec8e2be1f [spirv] Add OpControlBarrier and OpMemoryBarrier.
Add OpControlBarrier and OpMemoryBarrier (de)serialization.

Closes tensorflow/mlir#130

COPYBARA_INTEGRATE_REVIEW=https://github.com/tensorflow/mlir/pull/130 from denis0x0D:sandbox/memory_barrier 2e3fff16bca44904dc1039592cb9a65d526faea8
PiperOrigin-RevId: 270457478
2019-09-21 10:18:34 -07:00
River Riddle 3a643de92b NFC: Pass OpAsmPrinter by reference instead of by pointer.
MLIR follows the LLVM style of pass-by-reference.

PiperOrigin-RevId: 270401378
2019-09-20 20:43:35 -07:00
River Riddle 729727ebc7 NFC: Pass OperationState by reference instead of by pointer.
MLIR follows the LLVM convention of passing by reference instead of by pointer.

PiperOrigin-RevId: 270396945
2019-09-20 19:47:32 -07:00
River Riddle 2797517ecf NFC: Pass OpAsmParser by reference instead of by pointer.
MLIR follows the LLVM style of pass-by-reference.

PiperOrigin-RevId: 270315612
2019-09-20 11:37:21 -07:00
Prakalp Srivastava 5f86dc5fc9 NFC: Fix return indentation in generated op definitions.
PiperOrigin-RevId: 270070670
2019-09-19 10:24:06 -07:00
Mahesh Ravishankar 2d86ad79f0 Autogenerate (de)serialization for Extended Instruction Sets
A generic mechanism for (de)serialization of extended instruction sets
is added with this CL. To facilitate this, a new class
"SPV_ExtendedInstSetOp" is added which is a base class for all
operations corresponding to extended instruction sets. The methods to
(de)serialization such ops as well as its dispatch is generated
automatically.

The behavior controlled by autogenSerialization and hasOpcode is also
slightly modified to enable this. They are now decoupled.
1) Setting hasOpcode=1 means the operation has a corresponding
   opcode in SPIR-V binary format, and its dispatch for
   (de)serialization is automatically generated.
2) Setting autogenSerialization=1 generates the function for
   (de)serialization automatically.
So now it is possible to have hasOpcode=0 and autogenSerialization=1
(for example SPV_ExtendedInstSetOp).

Since the dispatch functions is also auto-generated, the input file
needs to contain all operations. To this effect, SPIRVGLSLOps.td is
included into SPIRVOps.td. This makes the previously added
SPIRVGLSLOps.h and SPIRVGLSLOps.cpp unnecessary, and are deleted.

The SPIRVUtilsGen.cpp is also changed to make better use of
formatv,making the code more readable.

PiperOrigin-RevId: 269456263
2019-09-16 17:12:33 -07:00
Lei Zhang 6934a337f0 [spirv] Add support for BitEnumAttr
Certain enum classes in SPIR-V, like function/loop control and memory
access, are bitmasks. This CL introduces a BitEnumAttr to properly
model this and drive auto-generation of verification code and utility
functions. We still store the attribute using an 32-bit IntegerAttr
for minimal memory footprint and easy (de)serialization. But utility
conversion functions are adjusted to inspect each bit and generate
"|"-concatenated strings for the bits; vice versa.

Each such enum class has a "None" case that means no bit is set. We
need special handling for "None". Because of this, the logic is not
general anymore. So right now the definition is placed in the SPIR-V
dialect. If later this turns out to be useful for other dialects,
then we can see how to properly adjust it and move to OpBase.td.

Added tests for SPV_MemoryAccess to check and demonstrate.

PiperOrigin-RevId: 269350620
2019-09-16 09:23:22 -07:00
MLIR Team d3787e5865 Improve verifier error reporting on type mismatch (NFC)
Before this change, it only reports expected type but not exact type, so
it's hard to troubleshoot.

PiperOrigin-RevId: 268961078
2019-09-13 12:46:34 -07:00
Rob Suderman 8f90a442c3 Added a TableGen generator for structured data
Similar to enum, added a generator for structured data. This provide Dictionary that stores a fixed set of values and guarantees the values are valid. It is intended to store a fixed number of values by a given name.

PiperOrigin-RevId: 266437460
2019-08-30 12:52:13 -07:00
River Riddle 140b28ec12 NFC: Avoid reconstructing the OpInterface methods.
PiperOrigin-RevId: 264881293
2019-08-22 11:31:27 -07:00
River Riddle b9377d7ec6 Add support for generating operation interfaces from the ODS framework.
Operation interfaces generally require a bit of boilerplate code to connect all of the pieces together. This cl introduces mechanisms in the ODS to allow for generating operation interfaces via the 'OpInterface' class.

Providing a definition of the `OpInterface` class will auto-generate the c++
classes for the interface. An `OpInterface` includes a name, for the c++ class,
along with a list of interface methods. There are two types of methods that can be used with an interface, `InterfaceMethod` and `StaticInterfaceMethod`. They are both comprised of the same core components, with the distinction that `StaticInterfaceMethod` models a static method on the derived operation.

An `InterfaceMethod` is comprised of the following components:
    * ReturnType
      - A string corresponding to the c++ return type of the method.
    * MethodName
      - A string corresponding to the desired name of the method.
    * Arguments
      - A dag of strings that correspond to a c++ type and variable name
        respectively.
    * MethodBody (Optional)
      - An optional explicit implementation of the interface method.

def MyInterface : OpInterface<"MyInterface"> {
  let methods = [
    // A simple non-static method with no inputs.
    InterfaceMethod<"unsigned", "foo">,

    // A new non-static method accepting an input argument.
    InterfaceMethod<"Value *", "bar", (ins "unsigned":$i)>,

    // Query a static property of the derived operation.
    StaticInterfaceMethod<"unsigned", "fooStatic">,

    // Provide the definition of a static interface method.
    // Note: `ConcreteOp` corresponds to the derived operation typename.
    StaticInterfaceMethod<"Operation *", "create",
      (ins "OpBuilder &":$builder, "Location":$loc), [{
        return builder.create<ConcreteOp>(loc);
    }]>,

    // Provide a definition of the non-static method.
    // Note: `op` corresponds to the derived operation variable.
    InterfaceMethod<"unsigned", "getNumInputsAndOutputs", (ins), [{
      return op.getNumInputs() + op.getNumOutputs();
    }]>,
  ];

PiperOrigin-RevId: 264754898
2019-08-21 20:57:51 -07:00
Lei Zhang 31cfee6077 Support variadic ops in declarative rewrite rules
This CL extends declarative rewrite rules to support matching and
generating ops with variadic operands/results. For this, the
generated `matchAndRewrite()` method for each pattern now are
changed to

* Use "range" types for the local variables used to store captured
  values (`operand_range` for operands, `ArrayRef<Value *>` for
  values, *Op for results). This allows us to have a unified way
  of handling both single values and value ranges.
* Create local variables for each operand for op creation. If the
  operand is variadic, then a `SmallVector<Value*>` will be created
  to collect all values for that operand; otherwise a `Value*` will
  be created.
* Use a collective result type builder. All result types are
  specified via a single parameter to the builder.

We can use one result pattern to replace multiple results of the
matched root op. When that happens, it will require specifying
types for multiple results. Add a new collective-type builder.

PiperOrigin-RevId: 264588559
2019-08-21 05:35:32 -07:00
River Riddle e152f0194f NFC: Don't assume that all operation traits are within the 'OpTrait::' namespace.
This places an unnecessary restriction that all traits are within this namespace.

PiperOrigin-RevId: 264212000
2019-08-19 12:13:18 -07:00
Jacques Pienaar 33a8642f53 InitLLVM already initializes PrettyStackTraceProgram
Remove extra PrettyStackTraceProgram and use InitLLVM consistently.

PiperOrigin-RevId: 264041205
2019-08-18 11:32:52 -07:00
Ben Vanik ae9ec43e46 Allow the use of the $cppClass template variable in verifier code blocks.
PiperOrigin-RevId: 263378198
2019-08-14 10:30:59 -07:00
Lei Zhang ac68637ba9 NFC: Refactoring PatternSymbolResolver into SymbolInfoMap
In declarative rewrite rules, a symbol can be bound to op arguments or
results in the source pattern, and it can be bound to op results in the
result pattern. This means given a symbol in the pattern, it can stands
for different things: op operand, op attribute, single op result,
op result pack. We need a better way to model this complexity so that
we can handle according to the specific kind a symbol corresponds to.

Created SymbolInfo class for maintaining the information regarding a
symbol. Also created a companion SymbolInfoMap class for a map of
such symbols, providing insertion and querying depending on use cases.

PiperOrigin-RevId: 262675515
2019-08-09 19:04:23 -07:00
Alex Zinenko baa1ec22f7 Translation to LLVM IR: use LogicalResult instead of bool
The translation code predates the introduction of LogicalResult and was relying
on the obsolete LLVM convention of returning false on success.  Change it to
use MLIR's LogicalResult abstraction instead. NFC.

PiperOrigin-RevId: 262589432
2019-08-09 10:45:44 -07:00
Lei Zhang 60f78453d7 Emit matchAndRewrite() for declarative rewrite rules
Previously we are emitting separate match() and rewrite()
methods, which requires conveying a match state struct
in a unique_ptr across these two methods. Changing to
emit matchAndRewrite() simplifies the picture.

PiperOrigin-RevId: 261906804
2019-08-06 07:11:08 -07:00
Lei Zhang cd1c488ecd [spirv] Provide decorations in batch for op construction
Instead of setting the attributes for decorations one by one
after constructing the op, this CL changes to attach all
the attributes for decorations to the attribute vector for
constructing the op. This should be simpler and more
efficient.

PiperOrigin-RevId: 261905578
2019-08-06 07:02:59 -07:00
River Riddle a0df3ebd15 NFC: Implement OwningRewritePatternList as a class instead of a using directive.
This allows for proper forward declaration, as opposed to leaking the internal implementation via a using directive. This also allows for all pattern building to go through 'insert' methods on the OwningRewritePatternList, replacing uses of 'push_back' and 'RewriteListBuilder'.

PiperOrigin-RevId: 261816316
2019-08-05 18:38:22 -07:00
Lei Zhang c72d849eb9 Replace the verifyUnusedValue directive with HasNoUseOf constraint
verifyUnusedValue is a bit strange given that it is specified in a
result pattern but used to generate match statements. Now we are
able to support multi-result ops better, we can retire it and replace
it with a HasNoUseOf constraint. This reduces the number of mechanisms.

PiperOrigin-RevId: 261166863
2019-08-01 11:51:15 -07:00
Lei Zhang e032d0dc63 Fix support for auxiliary ops in declarative rewrite rules
We allow to generate more ops than what are needed for replacing
the matched root op. Only the last N static values generated are
used as replacement; the others serve as auxiliary ops/values for
building the replacement.

With the introduction of multi-result op support, an op, if used
as a whole, may be used to replace multiple static values of
the matched root op. We need to consider this when calculating
the result range an generated op is to replace.

For example, we can have the following pattern:

```tblgen
def : Pattern<(ThreeResultOp ...),
              [(OneResultOp ...), (OneResultOp ...), (OneResultOp ...)]>;

// Two op to replace all three results
def : Pattern<(ThreeResultOp ...),
              [(TwoResultOp ...), (OneResultOp ...)]>;

// One op to replace all three results
def : Pat<(ThreeResultOp ...), (ThreeResultOp ...)>;

def : Pattern<(ThreeResultOp ...),
              [(AuxiliaryOp ...), (ThreeResultOp ...)]>;
```
PiperOrigin-RevId: 261017235
2019-07-31 16:03:42 -07:00
Lei Zhang e44ba1f8bf NFC: refactor ODS builder generation
Previously we use one single method with lots of branches to
generate multiple builders. This makes the method difficult
to follow and modify. This CL splits the method into multiple
dedicated ones, by extracting common logic into helper methods
while leaving logic specific to each builder in their own
methods.

PiperOrigin-RevId: 261011082
2019-07-31 15:31:13 -07:00
Mahesh Ravishankar cf66d7bb74 Use operand number during serialization to get the <id>s of the operands
During serialization, the operand number must be used to get the
values assocaited with an operand. Using the argument number in Op
specification was wrong since some of the elements in the arguments
list might be attributes on the operation. This resulted in a segfault
during serialization.
Add a test that exercise that path.

PiperOrigin-RevId: 260977758
2019-07-31 12:34:51 -07:00
Mahesh Ravishankar 1de519a753 Add support for (de)serialization of SPIR-V Op Decorations
All non-argument attributes specified for an operation are treated as
decorations on the result value and (de)serialized using OpDecorate
instruction. An error is generated if an attribute is not an argument,
and the name doesn't correspond to a Decoration enum. Name of the
attributes that represent decoerations are to be the snake-case-ified
version of the Decoration name.
Add utility methods to convert to snake-case and camel-case.

PiperOrigin-RevId: 260792638
2019-07-30 14:15:03 -07:00
Mahesh Ravishankar ea56025f1e Initial implementation to translate kernel fn in GPU Dialect to SPIR-V Dialect
This CL adds an initial implementation for translation of kernel
function in GPU Dialect (used with a gpu.launch_kernel) op to a
spv.Module. The original function is translated into an entry
function.
Most of the heavy lifting is done by adding TypeConversion and other
utility functions/classes that provide most of the functionality to
translate from Standard Dialect to SPIR-V Dialect. These are intended
to be reusable in implementation of different dialect conversion
pipelines.
Note : Some of the files for have been renamed to be consistent with
the norm used by the other Conversion frameworks.
PiperOrigin-RevId: 260759165
2019-07-30 11:55:55 -07:00
Alex Zinenko c7dab559ba RewriterGen: properly handle zero-result ops
RewriterGen was emitting invalid C++ code if the pattern required to create a
zero-result operation due to the absence of a special case that would avoid
generating a spurious comma.  Handle this case.  Also add rewriter tests for
zero-argument operations.

PiperOrigin-RevId: 260576998
2019-07-30 06:17:50 -07:00
Mahesh Ravishankar 673bb7cbbe Enable (de)serialization support for spirv::AccessChainOp
Automatic generation of spirv::AccessChainOp (de)serialization needs
the (de)serialization emitters to handle argument specified as
Variadic<...>. To handle this correctly, this argument can only be
the last entry in the arguments list.
Add a test to (de)serialize spirv::AccessChainOp

PiperOrigin-RevId: 260532598
2019-07-30 06:17:19 -07:00
Mehdi Amini b2c2b4bb1d [mlir-tblgen] Emit forward declarations for all the classes before the definitions
This allows classes to refer to each other in the ODS file, for instance for traits.

PiperOrigin-RevId: 260532419
2019-07-30 06:17:03 -07:00
Lei Zhang 9f02e88946 Support referencing a single value generated by a matched multi-result op
It's quite common that we want to put further constraints on the matched
multi-result op's specific results. This CL enables referencing symbols
bound to source op with the `__N` syntax.

PiperOrigin-RevId: 260122401
2019-07-26 04:31:46 -07:00
Lei Zhang 9d52ceaf16 [spirv] NFC: adjust `encode*` function signatures in Serializer
* Let them return `LogicalResult` so we can chain them together
  with other functions returning `LogicalResult`.
* Added "Into" as the suffix to the function name and made the
  `binary` as the first parameter so that it reads more naturally.

PiperOrigin-RevId: 259311636
2019-07-22 06:01:19 -07:00
Lei Zhang 17c18840da [spirv] Remove one level of indirection: processOp to processOpImpl
We already have two levels of controls in SPIRVBase.td: hasOpcode and
autogenSerialization. The former controls whether to add an entry to
the dispatch table, while the latter controls whether to autogenerate
the op's (de)serialization method specialization. This is enough for
our cases. Remove the indirection from processOp to processOpImpl
to simplify the picture.

PiperOrigin-RevId: 259308711
2019-07-22 05:37:39 -07:00
Mahesh Ravishankar 2fb53e65ab Add (de)serialization of EntryPointOp and ExecutionModeOp
Since the serialization of EntryPointOp contains the name of the
function as well, the function serialization emits the function name
using OpName instruction, which is used during deserialization to get
the correct function name.

PiperOrigin-RevId: 259158784
2019-07-20 18:12:05 -07:00
Lei Zhang e239f9647e Suppress compiler warnings regarding unused variables
Not all ops have operands or results, so it ends up there may be no
use of wordIndex or the generated op's results.

PiperOrigin-RevId: 258984485
2019-07-19 11:41:34 -07:00
Mahesh Ravishankar c6cfebf1af Automatically generate (de)serialization methods for SPIR-V ops
For ops in SPIR-V dialect that are a direct mirror of SPIR-V
operations, the serialization/deserialization methods can be
automatically generated from the Op specification. To enable this an
'autogenSerialization' field is added to SPV_Ops. When set to
non-zero, this will enable the automatic (de)serialization function
generation

Also adding tests that verify the spv.Load, spv.Store and spv.Variable
ops are serialized and deserialized correctly. To fully support these
tests also add serialization and deserialization of float types and
spv.ptr types

PiperOrigin-RevId: 258684764
2019-07-19 11:39:22 -07:00
Mahesh Ravishankar 9af156757d Add serialization and deserialization of FuncOps. To support this the
following SPIRV Instructions serializaiton/deserialization are added
as well

OpFunction
OpFunctionParameter
OpFunctionEnd
OpReturn

PiperOrigin-RevId: 257869806
2019-07-12 17:43:03 -07:00
Mahesh Ravishankar 801efec9e6 Update the gen_spirv_dialect.py script to add opcodes from the SPIR-V
JSON spec into the SPIRBase.td file. This is done incrementally to
only import those opcodes that are needed, through use of the script
define_opcode.sh added.

PiperOrigin-RevId: 257517343
2019-07-12 08:43:09 -07:00
River Riddle 8c44367891 NFC: Rename Function to FuncOp.
PiperOrigin-RevId: 257293379
2019-07-10 10:10:53 -07:00
Alex Zinenko ead1acaef2 ODS: provide a flag to skip generation of default build methods
Some operations need to override the default behavior of builders, in
particular region-holding operations such as affine.for or tf.graph want to
inject default terminators into the region upon construction, which default
builders won't do.  Provide a flag that disables the generation of default
builders so that the custom builders could use the same function signatures.
This is an intentionally low-level and heavy-weight feature that requires the
entire builder to be implemented, and it should be used sparingly.  Injecting
code into the end of a default builder would depend on the naming scheme of the
default builder arguments that is not visible in the ODS.  Checking that the
signature of a custom builder conflicts with that of a default builder to
prevent emission would require teaching ODG to differentiate between types and
(optional) argument names in the generated C++ code.  If this flag ends up
being used a lot, we should consider adding traits that inject specific code
into the default builder.

PiperOrigin-RevId: 256640069
2019-07-05 02:28:05 -07:00
Nicolas Vasilache 8c6a3ace16 Add ODS accessors for named regions.
PiperOrigin-RevId: 256639471
2019-07-05 02:21:06 -07:00
Mahesh Ravishankar 82679d4718 NFC: Refactoring to remove code bloat in SPIRV due to handling of Enum
Class Attribute parsing

PiperOrigin-RevId: 256471248
2019-07-03 18:18:01 -07:00
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
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
MLIR Team 7b5f49af76 Parenthesize match expression to avoid operator precedence issues
PiperOrigin-RevId: 255435454
2019-06-27 11:07:07 -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
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
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
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
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 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
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
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
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
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 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
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
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
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
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
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
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
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
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 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
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 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
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
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
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
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
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
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
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
Jacques Pienaar 4c0faef943 Avoid redundant predicate checking in type matching.
Expand type matcher template generator to consider a set of predicates that are known to
hold. This avoids inserting redundant checking for trivially true predicates
(for example predicate that hold according to the op definition). This only targets predicates that trivially holds and does not attempt any logic equivalence proof.

PiperOrigin-RevId: 228880468
2019-03-29 15:09:25 -07:00
Jacques Pienaar 88e1b9c792 Fix error in checking logic and update tests.
* Check was returning success instead of failure when reporting illegal type;
* TFL ops only support tensor types so update tests with corrected logic.
  - Removed some checks in broadcasting that don't work with tensor input requirement;

PiperOrigin-RevId: 228770184
2019-03-29 15:08:10 -07:00
Lei Zhang e49e10e4de Replace getAttributeName() with .getName()
PiperOrigin-RevId: 228581178
2019-03-29 15:06:56 -07:00
Lei Zhang 9b034f0bfd Add tblgen::Attribute to wrap around TableGen Attr defs
This CL added a tblgen::Attribute class to wrap around raw TableGen
Record getValue*() calls on Attr defs, which will provide a nicer
API for handling TableGen Record.

PiperOrigin-RevId: 228581107
2019-03-29 15:06:41 -07:00
Lei Zhang 3e5ee82b81 Put Operator and PredCNF into the tblgen namespace
PiperOrigin-RevId: 228429130
2019-03-29 15:05:38 -07:00
Lei Zhang b2cc2c344e Add tblgen::Type to wrap around TableGen Type defs
This CL added a tblgen::Type class to wrap around raw TableGen
Record getValue*() calls on Type defs, which will provide a
nicer API for handling TableGen Record.

The PredCNF class is also updated to work together with
tblgen::Type.
PiperOrigin-RevId: 228429090
2019-03-29 15:05:23 -07:00
Jacques Pienaar aae85ddce1 Match attributes in input pattern.
Bind attributes similar to operands. Use to rewrite leakyreulo and const rewrite pattern. The attribute type/attributes are not currently checked so should only be used where the attributes match due to the construction of the op.

To support current attribute namespacing, convert __ in attribute name to "$" for matching purposes ('$' is not valid character in variable in TableGen).

Some simplification to make it simpler to specify indented ostream and avoid so many spaces. The goal is not to have perfectly formatted code generated but good enough so that its still easy to read for a user.

PiperOrigin-RevId: 228183639
2019-03-29 15:00:55 -07:00
Jacques Pienaar 8f24943826 Verify type of operands match those specifed in op registry.
Expand type to include matcher predicates. Use CNF form to allow specifying combinations of constraints for type. The matching call for the type is used to verify the construction of the operation as well as in rewrite pattern generation.

The matching initially includes redundant checks (e.g., even if the operand of the op is guaranteed to satisfy some requirement, it is still checked during matcher generation for now). As well as some of the traits specified now check what the generated code already checks. Some of the traits can be removed in future as the verify method will include the relevant checks based on the op definition already.

More work is needed for variadic operands.

CNF form is used so that in the follow up redundant checks in the rewrite patterns could be omitted (e.g., when matching a F32Tensor, one does not need to verify that op X's operand 0 is a Tensor if that is guaranteed by op X's definition). The alternative was to have single matcher function specified, but this would not allow for reasoning about what attributes already hold (at the level of PredAtoms).

Use this new operand type restrictions to rewrite BiasAdd with floating point operands as declarative pattern.

PiperOrigin-RevId: 227991412
2019-03-29 14:58:23 -07:00
Lei Zhang ca88ea6f08 Fix format for empty method definition
PiperOrigin-RevId: 227840511
2019-03-29 14:55:52 -07:00
Alex Zinenko 8281151c2a TableGen standard arithmetic ops
Use tablegen to generate definitions of the standard binary arithmetic
operations.  These operations share a lot of boilerplate that is better off
generated by a tool.

Using tablegen for standard binary arithmetic operations requires the following
modifications.
1. Add a bit field `hasConstantFolder` to the base Op tablegen class; generate
the `constantFold` method signature if the bit is set.  Differentiate between
single-result and zero/multi-result functions that use different signatures.
The implementation of the method remains in C++, similarly to canonicalization
patterns, since it may be large and non-trivial.
2. Define the `AnyType` record of class `Type` since `BinaryOp` currently
provided in op_base.td is supposed to operate on tensors and other tablegen
users may rely on this behavior.

Note that this drops the inline documentation on the operation classes that was
copy-pasted around anyway.  Since we don't generate g3doc from tablegen yet,
keep LangRef.md as it is.  Eventually, the user documentation can move to the
tablegen definition file as well.

PiperOrigin-RevId: 227820815
2019-03-29 14:55:37 -07:00
Jacques Pienaar dde5bf234d Use Operator class in OpDefinitionsGen. Cleanup NFC.
PiperOrigin-RevId: 227764826
2019-03-29 14:55:22 -07:00
Jacques Pienaar c396c044e6 Match the op via isa instead of string compare.
* Match using isa
  - This limits the rewrite pattern to ops defined in op registry but that is probably better end state (esp. for additional verification).

PiperOrigin-RevId: 227598946
2019-03-29 14:53:37 -07:00
Jacques Pienaar 5c869951ac Add tf.Add op
Add ops.td for TF dialect and start by adding tf.Add (op used in legalizer pattern). This CL does not add TensorOp trait (that's not part of OpTrait namespace).

Remove OpCode emission that is not currently used and can be added back later if needed.

PiperOrigin-RevId: 227590973
2019-03-29 14:53:22 -07:00
Jacques Pienaar 3633becf8a Add builderCall to Type and add constant attr class.
With the builder to construct the type on the Type, the appropriate mlir::Type can be constructed where needed. Also add a constant attr class that has the attribute and value as members.

PiperOrigin-RevId: 227564789
2019-03-29 14:52:37 -07:00
Smit Hinsu 8f4c1e9f6d Indent auto-generated build method
TESTED manually

PiperOrigin-RevId: 227495854
2019-03-29 14:50:38 -07:00
Jacques Pienaar bbe3f4d9f5 Switch rewriters for relu, relu6, placeholder_input, softmax to patterns.
Add a constant F32 attribute for use with softmax legalization.

PiperOrigin-RevId: 227241643
2019-03-29 14:46:44 -07:00
Jacques Pienaar 554848d617 Match multiple pattern nodes as input to rewrite.
* Allow multi input node patterns in the rewrite;
* Use number of nodes matched as benefit;
* Rewrite relu(add(...)) matching using the new pattern;

To allow for undefined ops, do string compare - will address soon!

PiperOrigin-RevId: 227225425
2019-03-29 14:45:14 -07:00
Jacques Pienaar 2a463c36b1 Add convenience wrapper for operator in tblgen
Add convenience wrapper to make it easier to iterate over attributes and operands of operator defined in TableGen file. Use this class in RewriterGen (not used in the op generator yet, will do shortly). Change the RewriterGen to pass the bound arguments explicitly, this is in preparation for multi-op matching.

PiperOrigin-RevId: 227156748
2019-03-29 14:43:43 -07:00
Chris Lattner d798f9bad5 Rename BBArgument -> BlockArgument, Op::getOperation -> Op::getInst(),
StmtResult -> InstResult, StmtOperand -> InstOperand, and remove the old names.

This is step 17/n towards merging instructions and statements, NFC.

PiperOrigin-RevId: 227121537
2019-03-29 14:42:40 -07:00
Chris Lattner 5187cfcf03 Merge Operation into OperationInst and standardize nomenclature around
OperationInst.  This is a big mechanical patch.

This is step 16/n towards merging instructions and statements, NFC.

PiperOrigin-RevId: 227093712
2019-03-29 14:42:23 -07:00
Chris Lattner 3f190312f8 Merge SSAValue, CFGValue, and MLValue together into a single Value class, which
is the new base of the SSA value hierarchy.  This CL also standardizes all the
nomenclature and comments to use 'Value' where appropriate.  This also eliminates a large number of cast<MLValue>(x)'s, which is very soothing.

This is step 11/n towards merging instructions and statements, NFC.

PiperOrigin-RevId: 227064624
2019-03-29 14:40:06 -07:00
Jacques Pienaar 150b1a859e Merge mlir-op-gen and mlir-rewriter-gen into mlir-tblgen.
Unify the two tools before factoring out helper classes.

PiperOrigin-RevId: 227015406
2019-03-29 14:39:05 -07:00