Commit Graph

398 Commits

Author SHA1 Message Date
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