platform/upstream/llvm.git
5 years agoAdd rudimentary pattern rewrite matching generation.
Jacques Pienaar [Wed, 12 Dec 2018 11:09:11 +0000 (03:09 -0800)]
Add rudimentary pattern rewrite matching generation.

* Start very basic (about as basic as possible) with the pattern rewrite generation by only
  - Matching single node dags,
  - Single output, single result,
  - No constraints on inputs/outputs.
  - No attributes (only operands)
* The matcher generates C++ code akin to what is currently manually written.
  - This is very much not the final end state, and only intended for the short term;
* Always generate the default builder method to make it easier to generate calls;
  - Also add additional builder method for TFL::Add as attributes are not yet supported;
* Replace TF Add -> TFL Add matching using this generation;
* Introduce a conceptual textual namespace in the op registry
  - Will allow importing multiple dialect's op registry
  - Avoids needing to do anything special with tablegen or define a custom DSL;
    = I really want to do a custom DSL but this urge could just be as its fun :) So defer for now. From this structure we can dump out another structured form if needed;
  - Add a mapping from <namespace>_<op> in the op_gen and pattern rewrite gen
    = This allows placing ops in different namespaces from the same op registry which is convenient, esp. if we want to consider subnamespaces in future;
* Update tfl namespace to TFL to match TF and XLA;

PiperOrigin-RevId: 225155164

5 years agoRemove dead code from FlatAffineConstraints
Uday Bondhugula [Tue, 11 Dec 2018 22:49:58 +0000 (14:49 -0800)]
Remove dead code from FlatAffineConstraints

- getDimensionBounds() was added initially for quick experimentation - no
  longer used (getConstantBoundOnDimSize is the more powerful/complete
  replacement).
- FlatAffineConstraints::getConstantLower/UpperBound are incomplete,
  functionality/naming-wise misleading, and not used currently. Removing these;
  complete/fixed version will be added in an upcoming CL.

PiperOrigin-RevId: 225075061

5 years agoGenerate another op builder with aggregated parameters
Lei Zhang [Tue, 11 Dec 2018 21:59:29 +0000 (13:59 -0800)]
Generate another op builder with aggregated parameters

For each op, generate another builder with the following signature:

  static void build(Builder* builder, OperationState* result,
                    ArrayRef<Type> resultTypes,
                    ArrayRef<SSAValue*> args,
                    ArrayRef<NamedAttribute> attributes);

PiperOrigin-RevId: 225066007

5 years agoDisallow index types as elements of vector, memref and tensor types
Alex Zinenko [Tue, 11 Dec 2018 21:49:43 +0000 (13:49 -0800)]
Disallow index types as elements of vector, memref and tensor types

An extensive discussion demonstrated that it is difficult to support `index`
types as elements of compound (vector, memref, tensor) types.  In particular,
their size is unknown until the target-specific lowering takes place.  MLIR may
need to store constants of the fixed-shape compound types (e.g.,
vector<4 x index>) internally and must know the size of the element type and
data layout constraints.  The same information is necessary for target-specific
lowering and translation to reliably support compound types with `index`
elements, but MLIR does not have a dedicated target description mechanism yet.

The uses cases for compound types with `index` elements, should they appear,
can be handled via an `index_cast` operation that converts between `index` and
fixed-size integer types at the SSA value level instead of the type level.

PiperOrigin-RevId: 225064373

5 years agoUpdate/Fix LoopUtils::stmtBodySkew to handle loop step.
Uday Bondhugula [Mon, 10 Dec 2018 23:17:25 +0000 (15:17 -0800)]
Update/Fix LoopUtils::stmtBodySkew to handle loop step.

- loop step wasn't handled and there wasn't a TODO or an assertion; fix this.
- rename 'delay' to shift for consistency/readability.
- other readability changes.
- remove duplicate attribute print for DmaStartOp; fix misplaced attribute
  print for DmaWaitOp
- add build method for AddFOp (unrelated to this CL, but add it anyway)

PiperOrigin-RevId: 224892958

5 years agoFix missing check for dependent DMAs in pipeline-data-transfer
Uday Bondhugula [Mon, 10 Dec 2018 21:14:28 +0000 (13:14 -0800)]
Fix missing check for dependent DMAs in pipeline-data-transfer

- adding a conservative check for now (TODO: use the dependence analysis pass
  once the latter is extended to deal with DMA ops). resolve an existing bug on
  a test case.

- update test cases

PiperOrigin-RevId: 224869526

5 years agoFlatAffineConstraints API cleanup; add normalizeConstraintsByGCD().
Uday Bondhugula [Mon, 10 Dec 2018 20:59:53 +0000 (12:59 -0800)]
FlatAffineConstraints API cleanup; add normalizeConstraintsByGCD().

- add method normalizeConstraintsByGCD
- call normalizeConstraintsByGCD() and GCDTightenInequalities() at the end of
  projectOut.
- remove call to GCDTightenInequalities() from getMemRefRegion
- change isEmpty() to check isEmptyByGCDTest() / hasInvalidConstraint() each
  time an identifier is eliminated (to detect emptiness early).
- make FourierMotzkinEliminate, gaussianEliminateId(s),
  GCDTightenInequalities() private
- improve / update stale comments

PiperOrigin-RevId: 224866741

5 years agoUpdate/fix -pipeline-data-transfer; fix b/120770946
Uday Bondhugula [Mon, 10 Dec 2018 19:39:31 +0000 (11:39 -0800)]
Update/fix -pipeline-data-transfer; fix b/120770946

- fix replaceAllMemRefUsesWith call to replace only inside loop body.
- handle the case where DMA buffers are dynamic; extend doubleBuffer() method
  to handle dynamically shaped DMA buffers (pass the right operands to AllocOp)
- place alloc's for DMA buffers at the depth at which pipelining is being done
  (instead of at top-level)
- add more test cases

PiperOrigin-RevId: 224852231

5 years agoProperly namespace createLowerAffineApply
Alex Zinenko [Mon, 10 Dec 2018 17:55:10 +0000 (09:55 -0800)]
Properly namespace createLowerAffineApply

This was missing from the original commit.  The implementation of
createLowerAffineApply was defined in the default namespace but declared in the
`mlir` namespace, which could lead to linking errors when it was used.  Put the
definition in `mlir` namespace.

PiperOrigin-RevId: 224830894

5 years ago[MLIR] Drop bug-prone global map indexed by MLFunction*
Nicolas Vasilache [Sat, 8 Dec 2018 03:00:25 +0000 (19:00 -0800)]
[MLIR] Drop bug-prone global map indexed by MLFunction*

PiperOrigin-RevId: 224610805

5 years agoExtend loop tiling utility to handle non-constant loop bounds and bounds that
Uday Bondhugula [Sat, 8 Dec 2018 01:35:49 +0000 (17:35 -0800)]
Extend loop tiling utility to handle non-constant loop bounds and bounds that
are a max/min of several expressions.

- Extend loop tiling to handle non-constant loop bounds and bounds that
  are a max/min of several expressions, i.e., bounds using multi-result affine
  maps

- also fix b/120630124 as a result (the IR was in an invalid state when tiled
  loop generation failed; SSA uses were created that weren't plugged into the IR).

PiperOrigin-RevId: 224604460

5 years agoGenerate strided DMAs from -dma-generate
Uday Bondhugula [Fri, 7 Dec 2018 23:04:55 +0000 (15:04 -0800)]
Generate strided DMAs from -dma-generate
- generate DMAs correctly now using strided DMAs where needed
- add support for multi-level/nested strides; op still supports one level of
  stride for now.

Other things
- add test case for  symbolic lower/upper bound; cases where the DMA buffer
  size can't be bounded by a known constant
- add test case for dynamic shapes where the DMA buffers are however bounded by
  constants
- refactor some of the '-dma-generate' code

PiperOrigin-RevId: 224584529

5 years ago[MLIR] Add LowerVectorTransfersPass
Nicolas Vasilache [Fri, 7 Dec 2018 19:48:54 +0000 (11:48 -0800)]
[MLIR] Add LowerVectorTransfersPass

This CL adds a pass that lowers VectorTransferReadOp and VectorTransferWriteOp
to a simple loop nest via local buffer allocations.

This is an MLIR->MLIR lowering based on builders.

A few TODOs are left to address in particular:
1. invert the permutation map so the accesses to the remote memref are coalesced;
2. pad the alloc for bank conflicts in local memory (e.g. GPUs shared_memory);
3. support broadcast / avoid copies when permutation_map is not of full column rank
4. add a proper "element_cast" op

One notable limitation is this does not plan on supporting boundary conditions.
It should be significantly easier to use pre-baked MLIR functions to handle such paddings.
This is left for future consideration.
Therefore the current CL only works properly for full-tile cases atm.

This CL also adds 2 simple tests:

```mlir
  for %i0 = 0 to %M step 3 {
    for %i1 = 0 to %N step 4 {
      for %i2 = 0 to %O {
        for %i3 = 0 to %P step 5 {
          vector_transfer_write %f1, %A, %i0, %i1, %i2, %i3 {permutation_map: (d0, d1, d2, d3) -> (d3, d1, d0)} : vector<5x4x3xf32>, memref<?x?x?x?xf32, 0>, index, index, index, index
```

lowers into:
```mlir
for %i0 = 0 to %arg0 step 3 {
  for %i1 = 0 to %arg1 step 4 {
    for %i2 = 0 to %arg2 {
      for %i3 = 0 to %arg3 step 5 {
        %1 = alloc() : memref<5x4x3xf32>
        %2 = "element_type_cast"(%1) : (memref<5x4x3xf32>) -> memref<1xvector<5x4x3xf32>>
        store %cst, %2[%c0] : memref<1xvector<5x4x3xf32>>
        for %i4 = 0 to 5 {
          %3 = affine_apply (d0, d1) -> (d0 + d1) (%i3, %i4)
          for %i5 = 0 to 4 {
            %4 = affine_apply (d0, d1) -> (d0 + d1) (%i1, %i5)
            for %i6 = 0 to 3 {
              %5 = affine_apply (d0, d1) -> (d0 + d1) (%i0, %i6)
              %6 = load %1[%i4, %i5, %i6] : memref<5x4x3xf32>
              store %6, %0[%5, %4, %i2, %3] : memref<?x?x?x?xf32>
       dealloc %1 : memref<5x4x3xf32>
```

and
```mlir
  for %i0 = 0 to %M step 3 {
    for %i1 = 0 to %N {
      for %i2 = 0 to %O {
        for %i3 = 0 to %P step 5 {
          %f = vector_transfer_read %A, %i0, %i1, %i2, %i3 {permutation_map: (d0, d1, d2, d3) -> (d3, 0, d0)} : (memref<?x?x?x?xf32, 0>, index, index, index, index) -> vector<5x4x3xf32>

```

lowers into:
```mlir
for %i0 = 0 to %arg0 step 3 {
  for %i1 = 0 to %arg1 {
    for %i2 = 0 to %arg2 {
      for %i3 = 0 to %arg3 step 5 {
        %1 = alloc() : memref<5x4x3xf32>
        %2 = "element_type_cast"(%1) : (memref<5x4x3xf32>) -> memref<1xvector<5x4x3xf32>>
        for %i4 = 0 to 5 {
          %3 = affine_apply (d0, d1) -> (d0 + d1) (%i3, %i4)
          for %i5 = 0 to 4 {
            for %i6 = 0 to 3 {
              %4 = affine_apply (d0, d1) -> (d0 + d1) (%i0, %i6)
              %5 = load %0[%4, %i1, %i2, %3] : memref<?x?x?x?xf32>
              store %5, %1[%i4, %i5, %i6] : memref<5x4x3xf32>
        %6 = load %2[%c0] : memref<1xvector<5x4x3xf32>>
        dealloc %1 : memref<5x4x3xf32>
```

PiperOrigin-RevId: 224552717

5 years ago[MLIR] Fix the name of the MaterializeVectorPass
Nicolas Vasilache [Fri, 7 Dec 2018 18:21:52 +0000 (10:21 -0800)]
[MLIR] Fix the name of the MaterializeVectorPass

PiperOrigin-RevId: 224536381

5 years ago[MLIR] Add composeWithUnboundedMap
Nicolas Vasilache [Fri, 7 Dec 2018 18:21:26 +0000 (10:21 -0800)]
[MLIR] Add composeWithUnboundedMap

This CL adds a finer grain composition function between AffineExpr and an
unbounded map. This will be used in the next CL.
Also cleans up some comments remaining from a previous CL.

PiperOrigin-RevId: 224536314

5 years ago[MLIR] Add LangRef entries for vector_transfer ops
Nicolas Vasilache [Fri, 7 Dec 2018 18:16:49 +0000 (10:16 -0800)]
[MLIR] Add LangRef entries for vector_transfer ops

PiperOrigin-RevId: 224535443

5 years agoReturn bool from all emitError methods similar to Operation::emitOpError
Smit Hinsu [Fri, 7 Dec 2018 17:30:25 +0000 (09:30 -0800)]
Return bool from all emitError methods similar to Operation::emitOpError

This simplifies call-sites returning true after emitting an error. After the
conversion, dropped braces around single statement blocks as that seems more
common.

Also, switched to emitError method instead of emitting Error kind using the
emitDiagnostic method.

TESTED with existing unit tests

PiperOrigin-RevId: 224527868

5 years agoAuto-generate op builder with TableGen
Lei Zhang [Thu, 6 Dec 2018 20:06:00 +0000 (12:06 -0800)]
Auto-generate op builder with TableGen

If no custom builder is supplied for an op, TableGen now generates
a default builder for it with the following signature:

  static void build(Builder *builder, OperationState* result,
                    <list-of-all-result-types>,
                    <list-of-all-operands>,
                    <list-of-all-attributes>);

PiperOrigin-RevId: 224382473

5 years ago[MLIR] Drop assert for NYI in Vectorize.cpp
Nicolas Vasilache [Thu, 6 Dec 2018 19:39:00 +0000 (11:39 -0800)]
[MLIR] Drop assert for NYI in Vectorize.cpp

This CLs adds proper error emission, removes NYI assertions and documents
assumptions that are required in the relevant functions.

PiperOrigin-RevId: 224377207

5 years ago[MLIR] Drop assert for NYI in VectorAnalysis
Nicolas Vasilache [Thu, 6 Dec 2018 19:38:44 +0000 (11:38 -0800)]
[MLIR] Drop assert for NYI in VectorAnalysis

This CLs adds proper error emission, removes NYI assertions and documents
assumptions that are required in the relevant functions.

PiperOrigin-RevId: 224377143

5 years ago[MLIR] Drop unnecessary mention of NYI.
Nicolas Vasilache [Thu, 6 Dec 2018 19:38:26 +0000 (11:38 -0800)]
[MLIR] Drop unnecessary mention of NYI.

This CL also documents the `substExpr` helper function assumptions.
The assumptions are properly propagated up already.

PiperOrigin-RevId: 224377072

5 years ago[MLIR] Remove NYI assertions in LoopAnalysis.cpp
Nicolas Vasilache [Thu, 6 Dec 2018 19:38:09 +0000 (11:38 -0800)]
[MLIR] Remove NYI assertions in LoopAnalysis.cpp

This CL also cleans up some loose ends and returns conservative answers while
emitting errors in the NYI cases.

PiperOrigin-RevId: 224377004

5 years ago[MLIR] Error handling in MaterializeVectors
Nicolas Vasilache [Thu, 6 Dec 2018 19:37:53 +0000 (11:37 -0800)]
[MLIR] Error handling in MaterializeVectors

This removes assertions as a means to capture NYI behavior and propagates
errors up.

PiperOrigin-RevId: 224376935

5 years ago[MLIR] Add AffineMap composition and use it in Materialization
Nicolas Vasilache [Thu, 6 Dec 2018 19:37:38 +0000 (11:37 -0800)]
[MLIR] Add AffineMap composition and use it in Materialization

This CL adds the following free functions:
```
/// Returns the AffineExpr e o m.
AffineExpr compose(AffineExpr e, AffineMap m);
/// Returns the AffineExpr f o g.
AffineMap compose(AffineMap f, AffineMap g);
```

This addresses the issue that AffineMap composition is only available at a
distance via AffineValueMap and is thus unusable on Attributes.
This CL thus implements AffineMap composition in a more modular and composable
way.

This CL does not claim that it can be a good replacement for the
implementation in AffineValueMap, in particular it does not support bounded
maps atm.

Standalone tests are added that replicate some of the logic of the AffineMap
composition pass.

Lastly, affine map composition is used properly inside MaterializeVectors and
a standalone test is added that requires permutation_map composition with a
projection map.

PiperOrigin-RevId: 224376870

5 years ago[MLIR] Add support for permutation_map
Nicolas Vasilache [Thu, 6 Dec 2018 19:37:25 +0000 (11:37 -0800)]
[MLIR] Add support for permutation_map

This CL hooks up and uses permutation_map in vector_transfer ops.
In particular, when going into the nuts and bolts of the implementation, it
became clear that cases arose that required supporting broadcast semantics.
Broadcast semantics are thus added to the general permutation_map.
The verify methods and tests are updated accordingly.

Examples of interest include.

Example 1:
The following MLIR snippet:
```mlir
   for %i3 = 0 to %M {
     for %i4 = 0 to %N {
       for %i5 = 0 to %P {
         %a5 = load %A[%i4, %i5, %i3] : memref<?x?x?xf32>
   }}}
```
may vectorize with {permutation_map: (d0, d1, d2) -> (d2, d1)} into:
```mlir
   for %i3 = 0 to %0 step 32 {
     for %i4 = 0 to %1 {
       for %i5 = 0 to %2 step 256 {
         %4 = vector_transfer_read %arg0, %i4, %i5, %i3
              {permutation_map: (d0, d1, d2) -> (d2, d1)} :
              (memref<?x?x?xf32>, index, index) -> vector<32x256xf32>
   }}}
````
Meaning that vector_transfer_read will be responsible for reading the 2-D slice:
`%arg0[%i4, %i5:%15+256, %i3:%i3+32]` into vector<32x256xf32>. This will
require a transposition when vector_transfer_read is further lowered.

Example 2:
The following MLIR snippet:
```mlir
   %cst0 = constant 0 : index
   for %i0 = 0 to %M {
     %a0 = load %A[%cst0, %cst0] : memref<?x?xf32>
   }
```
may vectorize with {permutation_map: (d0) -> (0)} into:
```mlir
   for %i0 = 0 to %0 step 128 {
     %3 = vector_transfer_read %arg0, %c0_0, %c0_0
          {permutation_map: (d0, d1) -> (0)} :
          (memref<?x?xf32>, index, index) -> vector<128xf32>
   }
````
Meaning that vector_transfer_read will be responsible of reading the 0-D slice
`%arg0[%c0, %c0]` into vector<128xf32>. This will require a 1-D vector
broadcast when vector_transfer_read is further lowered.

Additionally, some minor cleanups and refactorings are performed.

One notable thing missing here is the composition with a projection map during
materialization. This is because I could not find an AffineMap composition
that operates on AffineMap directly: everything related to composition seems
to require going through SSAValue and only operates on AffinMap at a distance
via AffineValueMap. I have raised this concern a bunch of times already, the
followup CL will actually do something about it.

In the meantime, the projection is hacked at a minimum to pass verification
and materialiation tests are temporarily incorrect.

PiperOrigin-RevId: 224376828

5 years agoConvertToCFG: support min/max in loop bounds.
Alex Zinenko [Thu, 6 Dec 2018 19:34:27 +0000 (11:34 -0800)]
ConvertToCFG: support min/max in loop bounds.

The recently introduced `select` operation enables ConvertToCFG to support
min(max) in loop bounds.  Individual min(max) is implemented as
`cmpi "lt"`(`cmpi "gt"`) followed by a `select` between the compared values.
Multiple results of an `affine_apply` operation extracted from the loop bounds
are reduced using min(max) in a sequential manner.  While this may decrease the
potential for instruction-level parallelism, it is easier to recognize for the
following passes, in particular for the vectorizer.

PiperOrigin-RevId: 224376233

5 years agoOpPointer: replace conversion operator to Operation* to OpType*.
Alex Zinenko [Thu, 6 Dec 2018 18:56:21 +0000 (10:56 -0800)]
OpPointer: replace conversion operator to Operation* to OpType*.

The implementation of OpPointer<OpType> provides an implicit conversion to
Operation *, but not to the underlying OpType *.  This has led to
awkward-looking code when an OpPointer needs to be passed to a function
accepting an OpType *.  For example,

    if (auto someOp = genericOp.dyn_cast<OpType>())
      someFunction(&*someOp);

where "&*" makes it harder to read.  Arguably, one does not want to spell out
OpPointer<OpType> in the line with dyn_cast.  More generally, OpPointer is now
being used as an owning pointer to OpType rather than to operation.

Replace the implicit conversion to Operation* with the conversion to OpType*
taking into account const-ness of the type.  An Operation* can be obtained from
an OpType with a simple call.  Since an instance of OpPointer owns the OpType
value, the pointer to it is never null.  However, the OpType value may not be
associated with any Operation*.  In this case, return nullptr when conversion
is attempted to maintain consistency with the existing null checks.

PiperOrigin-RevId: 224368103

5 years agoFix cases where unsigned / signed arithmetic was being mixed (following up on
Uday Bondhugula [Thu, 6 Dec 2018 04:34:23 +0000 (20:34 -0800)]
Fix cases where unsigned / signed arithmetic was being mixed (following up on
cl/224246657); eliminate repeated evaluation of exprs in loop upper bounds.

- while on this, sweep through and fix potential repeated evaluation of
  expressions in loop upper bounds

PiperOrigin-RevId: 224268918

5 years agoFix bug in GCD calculation when flattening AffineExpr (adds unit test which triggers...
MLIR Team [Thu, 6 Dec 2018 01:00:28 +0000 (17:00 -0800)]
Fix bug in GCD calculation when flattening AffineExpr (adds unit test which triggers the bug and tests the fix).

PiperOrigin-RevId: 224246657

5 years agoMake examples semantically meaningful and fix miscellaneous typos. Thanks to @rocky...
Tatiana Shpeisman [Thu, 6 Dec 2018 00:10:05 +0000 (16:10 -0800)]
Make examples semantically meaningful and fix miscellaneous typos. Thanks to @rocky for pointing out the bugs.

PiperOrigin-RevId: 224239160

5 years agoStrided DMA support for DmaStartOp
Uday Bondhugula [Wed, 5 Dec 2018 23:30:25 +0000 (15:30 -0800)]
Strided DMA support for DmaStartOp

- add optional stride arguments for DmaStartOp
- add DmaStartOp::verify(), and missing test cases for DMA op's in
  test/IR/memory-ops.mlir.

PiperOrigin-RevId: 224232466

5 years agoComplete multiple unhandled cases for DmaGeneration / getMemRefRegion;
Uday Bondhugula [Wed, 5 Dec 2018 23:14:25 +0000 (15:14 -0800)]
Complete multiple unhandled cases for DmaGeneration / getMemRefRegion;
update/improve/clean up API.

- update FlatAffineConstraints::getConstBoundDifference; return constant
  differences between symbolic affine expressions, look at equalities as well.
- fix buffer size computation when generating DMAs symbolic in outer loops,
  correctly handle symbols at various places (affine access maps, loop bounds,
  loop IVs outer to the depth at which DMA generation is being done)
- bug fixes / complete some TODOs for getMemRefRegion
- refactor common code b/w memref dependence check and getMemRefRegion
- FlatAffineConstraints API update; added methods employ trivial checks /
  detection - sufficient to handle hyper-rectangular cases in a precise way
  while being fast / low complexity. Hyper-rectangular cases fall out as
  trivial cases for these methods while other cases still do not cause failure
  (either return conservative or return failure that is handled by the caller).

PiperOrigin-RevId: 224229879

5 years agoClean up base TableGen definitions
Lei Zhang [Wed, 5 Dec 2018 22:34:25 +0000 (14:34 -0800)]
Clean up base TableGen definitions

* Removed unused builder field for type definitions
* Refined comments and reordered classes

PiperOrigin-RevId: 224223038

5 years agoEnable using bare attributes.
Jacques Pienaar [Wed, 5 Dec 2018 21:25:44 +0000 (13:25 -0800)]
Enable using bare attributes.

Useful for defining ops such as <dialect>.Const where multiple kinds of attributes are legal.

PiperOrigin-RevId: 224210511

5 years agoAdd isIntOrIndex() and isIntOrIndexOrFloat() into Type
Lei Zhang [Wed, 5 Dec 2018 12:31:59 +0000 (04:31 -0800)]
Add isIntOrIndex() and isIntOrIndexOrFloat() into Type

The checks for `isa<IndexType>() || isa<IntegerType>()` and
`isa<IndexType>() || isa<IntegerType>() || isa<FloatType>()`
are frequently used, so it's useful to have some helper
methods for them.

PiperOrigin-RevId: 224133596

5 years agoRemove duplicate FlatAffineConstraints::removeId - refactor to use
Uday Bondhugula [Tue, 4 Dec 2018 23:09:52 +0000 (15:09 -0800)]
Remove duplicate FlatAffineConstraints::removeId - refactor to use
removeColumnRange

- remove functionally duplicate code in removeId.

- rename removeColumnRange -> removeIdRange - restrict valid input to just the
  identifier columns (not the constant term column).

PiperOrigin-RevId: 224054064

5 years agoFlatAffineConstraints::removeId() fix.
Uday Bondhugula [Tue, 4 Dec 2018 21:09:45 +0000 (13:09 -0800)]
FlatAffineConstraints::removeId() fix.

This is an obvious bug, but none of the test cases exposed it since numIds was
correctly updated, and the dimensional identifiers were always eliminated
before the symbolic identifiers in all cases that removeId was getting
called from. However, other work in progress exercises the other scenarios and
exposes this bug.

Add an hasConsistentState() private method to move common assertion checks, and call it
from several base methods. Make hasInvalidConstraint() a private method as
well (from a file static one).

PiperOrigin-RevId: 224032721

5 years agoChange TFLite binary ops to support implicit broadcasting
Lei Zhang [Tue, 4 Dec 2018 20:37:28 +0000 (12:37 -0800)]
Change TFLite binary ops to support implicit broadcasting

As it turns out, the TFLite runtime already supports implicit broadcasting
for math binary ops. As the instruction set for TFLite runtime, the tfl
dialect should reflect that, instead of requiring both operands for binary
ops to be of the same type.

To support implicit broadcast means it's not suitable to provide the
short-form assembly for TFLite binary ops anymore. So by default, we should
just provide the canonical-form assembly parser/printer for base binary op.
It's subclasses' choices whether to opt in to short-form.

Added BroadcastableTwoOperandsOneResult as a new dialect trait for checking
the operand and result types for TFLite binary ops.

Also added SameOperandsAndResultType to several neural network ops.

PiperOrigin-RevId: 224027445

5 years agoDuring forward substitution, merge symbols from input AffineMap with the symbol list...
MLIR Team [Tue, 4 Dec 2018 19:40:37 +0000 (11:40 -0800)]
During forward substitution, merge symbols from input AffineMap with the symbol list of the target AffineMap.
Symbols can be used as dim identifiers and symbolic identifiers, and so we must preserve the symbolic identifies from the input AffineMap during forward substitution, even if that same identifier is used as a dimension identifier in the target AffineMap.
Test case added.

Going forward, we may want to explore solutions where we do not maintain this split between dimensions and symbols, and instead verify the validity of each use of each AffineMap operand AffineMap in the context where the AffineMap operand usage is required to be a symbol: in the denominator of floordiv/ceildiv/mod for semi-affine maps, and in instructions that can capture symbols (i.e. alloc)

PiperOrigin-RevId: 224017364

5 years agoFix off by one in OpStats.
Jacques Pienaar [Tue, 4 Dec 2018 15:57:33 +0000 (07:57 -0800)]
Fix off by one in OpStats.

PiperOrigin-RevId: 223977444

5 years agoConvertToCFG: convert "if" statements.
Alex Zinenko [Tue, 4 Dec 2018 15:04:44 +0000 (07:04 -0800)]
ConvertToCFG: convert "if" statements.

The condition of the "if" statement is an integer set, defined as a conjunction
of affine constraints.  An affine constraints consists of an affine expression
and a flag indicating whether the expression is strictly equal to zero or is
also allowed to be greater than zero.  Affine maps, accepted by `affine_apply`
are also formed from affine expressions.  Leverage this fact to implement the
checking of "if" conditions.  Each affine expression from the integer set is
converted into an affine map.  This map is applied to the arguments of the "if"
statement.  The result of the application is compared with zero given the
equality flag to obtain the final boolean value.  The conjunction of conditions
is tested sequentially with short-circuit branching to the "else" branch if any
of the condition evaluates to false.

Create an SESE region for the if statement (including its "then" and optional
"else" statement blocks) and append it to the end of the current region.  The
conditional region consists of a sequence of condition-checking blocks that
implement the short-circuit scheme, followed by a "then" SESE region and an
"else" SESE region, and the continuation block that post-dominates all blocks
of the "if" statement.  The flow of blocks that correspond to the "then" and
"else" clauses are constructed recursively, enabling easy nesting of "if"
statements and if-then-else-if chains.

Note that MLIR semantics does not require nor prohibit short-circuit
evaluation.  Since affine expressions do not have side effects, there is no
observable difference in the program behavior.  We may trade off extra
operations for operation-level parallelism opportunity by first performing all
`affine_apply` and comparison operations independently, and then performing a
tree pattern reduction of the resulting boolean values with the `muli i1`
operations (in absence of the dedicated bit operations).  The pros and cons are
not clear, and since MLIR does not include parallel semantics, we prefer to
minimize the number of sequentially executed operations.

PiperOrigin-RevId: 223970248

5 years agoLLVM IR Lowering: support multi-value returns.
Alex Zinenko [Tue, 4 Dec 2018 14:16:26 +0000 (06:16 -0800)]
LLVM IR Lowering: support multi-value returns.

Unlike MLIR, LLVM IR does not support functions that return multiple values.
Simulate this by packing values into the LLVM structure type in the same order
as they appear in the MLIR return.  If the function returns only a single
value, return it directly without packing.

PiperOrigin-RevId: 223964886

5 years ago[MLIR] Separate and split vectorization tests
Nicolas Vasilache [Mon, 3 Dec 2018 23:27:27 +0000 (15:27 -0800)]
[MLIR] Separate and split vectorization tests

These tests have become too bulky and unwiedly.
Splitting simplifies modifications that will occur in the next CL.

PiperOrigin-RevId: 223874321

5 years ago[MLIR] Add VectorTransferOps
Nicolas Vasilache [Mon, 3 Dec 2018 23:21:27 +0000 (15:21 -0800)]
[MLIR] Add VectorTransferOps

This CL implements and uses VectorTransferOps in lieu of the former custom
call op. Tests are updated accordingly.

VectorTransferOps come in 2 flavors: VectorTransferReadOp and
VectorTransferWriteOp.

VectorTransferOps can be thought of as a backend-independent
pseudo op/library call that needs to be legalized to MLIR (whiteboxed) before
it can be lowered to backend-dependent IR.

Note that the current implementation does not yet support a real permutation
map. Proper support will come in a followup CL.

VectorTransferReadOp
====================
VectorTransferReadOp performs a blocking read from a scalar memref
location into a super-vector of the same elemental type. This operation is
called 'read' by opposition to 'load' because the super-vector granularity
is generally not representable with a single hardware register. As a
consequence, memory transfers will generally be required when lowering
VectorTransferReadOp. A VectorTransferReadOp is thus a mid-level abstraction
that supports super-vectorization with non-effecting padding for full-tile
only code.

A vector transfer read has semantics similar to a vector load, with additional
support for:
  1. an optional value of the elemental type of the MemRef. This value
     supports non-effecting padding and is inserted in places where the
     vector read exceeds the MemRef bounds. If the value is not specified,
     the access is statically guaranteed to be within bounds;
  2. an attribute of type AffineMap to specify a slice of the original
     MemRef access and its transposition into the super-vector shape. The
     permutation_map is an unbounded AffineMap that must represent a
     permutation from the MemRef dim space projected onto the vector dim
     space.

Example:
```mlir
  %A = alloc(%size1, %size2, %size3, %size4) : memref<?x?x?x?xf32>
  ...
  %val = `ssa-value` : f32
  // let %i, %j, %k, %l be ssa-values of type index
  %v0 = vector_transfer_read %src, %i, %j, %k, %l
        {permutation_map: (d0, d1, d2, d3) -> (d3, d1, d2)} :
          (memref<?x?x?x?xf32>, index, index, index, index) ->
            vector<16x32x64xf32>
  %v1 = vector_transfer_read %src, %i, %j, %k, %l, %val
        {permutation_map: (d0, d1, d2, d3) -> (d3, d1, d2)} :
          (memref<?x?x?x?xf32>, index, index, index, index, f32) ->
            vector<16x32x64xf32>
```

VectorTransferWriteOp
=====================
VectorTransferWriteOp performs a blocking write from a super-vector to
a scalar memref of the same elemental type. This operation is
called 'write' by opposition to 'store' because the super-vector
granularity is generally not representable with a single hardware register. As
a consequence, memory transfers will generally be required when lowering
VectorTransferWriteOp. A VectorTransferWriteOp is thus a mid-level
abstraction that supports super-vectorization with non-effecting padding
for full-tile only code.
A vector transfer write has semantics similar to a vector store, with
additional support for handling out-of-bounds situations.

Example:
```mlir
  %A = alloc(%size1, %size2, %size3, %size4) : memref<?x?x?x?xf32>.
  %val = `ssa-value` : vector<16x32x64xf32>
  // let %i, %j, %k, %l be ssa-values of type index
  vector_transfer_write %val, %src, %i, %j, %k, %l
    {permutation_map: (d0, d1, d2, d3) -> (d3, d1, d2)} :
  (vector<16x32x64xf32>, memref<?x?x?x?xf32>, index, index, index, index)
```
PiperOrigin-RevId: 223873234

5 years agoFix two more getHashValues.
Jacques Pienaar [Mon, 3 Dec 2018 22:27:24 +0000 (14:27 -0800)]
Fix two more getHashValues.

These were still returning the hash of the pointers resulting in the two getHashValues being different.

PiperOrigin-RevId: 223862743

5 years agoFlatAffineConstraints::composeMap: return failure instead of asserting on semi-affine...
Uday Bondhugula [Mon, 3 Dec 2018 19:20:10 +0000 (11:20 -0800)]
FlatAffineConstraints::composeMap: return failure instead of asserting on semi-affine maps

FlatAffineConstraints::composeMap: should return false instead of asserting on
a semi-affine map. Make getMemRefRegion just propagate false when encountering
semi-affine maps (instead of crashing!)
PiperOrigin-RevId: 223828743

5 years agoMinor fix for replaceAllMemRefUsesWith.
Uday Bondhugula [Mon, 3 Dec 2018 19:15:24 +0000 (11:15 -0800)]
Minor fix for replaceAllMemRefUsesWith.

The check for whether the memref was used in a non-derefencing context had to
be done inside, i.e., only for the op stmt's that the replacement was specified
to be performed on (by the domStmtFilter arg if provided). As such, it is
completely fine for example for a function to return a memref while the replacement
is being performed only a specific loop's body (as in the case of DMA
generation).

PiperOrigin-RevId: 223827753

5 years agoAdd a simple common sub expression elimination pass.
River Riddle [Mon, 3 Dec 2018 17:45:35 +0000 (09:45 -0800)]
Add a simple common sub expression elimination pass.

The algorithm collects defining operations within a scoped hash table. The scopes within the hash table correspond to nodes within the dominance tree for a function. This cl only adds support for simple operations, i.e non side-effecting. Such operations, e.g. load/store/call, will be handled in later patches.

PiperOrigin-RevId: 223811328

5 years agoRemove tfl.reshape op when possible
Lei Zhang [Mon, 3 Dec 2018 17:16:59 +0000 (09:16 -0800)]
Remove tfl.reshape op when possible

Remove tfl.reshape for the following two cases:

1. A tfl.reshape's input is from another tfl.reshape.
   Then these two tfl.reshape ops can be merged.

2. A tfl.reshape's result type is the same as its input type.
   This tfl.reshape op does nothing, which can be removed.

These transformations are put in a new source file, Canonicalizer.cpp,
because they are TFLite op to TFLite op transformations, and aiming
to making TFLite ops more canonicalized.

Also added a hasCanonicalizationPatterns marker in TableGen Op class
to indicate whether an op has custom getCanonicalizationPatterns().

PiperOrigin-RevId: 223806921

5 years agoUpdate getHashValue for ptr values stored in a DenseMap/Set to use getHasValue of...
Jacques Pienaar [Sat, 1 Dec 2018 19:38:20 +0000 (11:38 -0800)]
Update getHashValue for ptr values stored in a DenseMap/Set to use getHasValue of KeyTy.

Ensures both hash values returned are the same. Tested by triggering resize of map/set and verifying failure before change.

PiperOrigin-RevId: 223651443

5 years agoRankedTensorType: Use getHashValue(KeyTy) when calling getHashValue(RankedTensorTypeS...
Jacques Pienaar [Sat, 1 Dec 2018 18:55:23 +0000 (10:55 -0800)]
RankedTensorType: Use getHashValue(KeyTy) when calling getHashValue(RankedTensorTypeStorage*).

PiperOrigin-RevId: 223649958

5 years agoDocument SelectOp class
Alex Zinenko [Fri, 30 Nov 2018 08:45:02 +0000 (00:45 -0800)]
Document SelectOp class

This was missing from the commit that introduced SelectOp although the
documentation was present in the LangRef.md.

PiperOrigin-RevId: 223476888

5 years agoAvoid failing when attempting to print null Attribute.
Jacques Pienaar [Fri, 30 Nov 2018 02:47:39 +0000 (18:47 -0800)]
Avoid failing when attempting to print null Attribute.

This avoids segfaulting when dumping during debugging of failures.

PiperOrigin-RevId: 223449494

5 years agoDebug output / logging memref sizes in DMA generation + related changes
Uday Bondhugula [Thu, 29 Nov 2018 23:25:40 +0000 (15:25 -0800)]
Debug output / logging memref sizes in DMA generation + related  changes

- Add method to get a memref's size in bytes
- clean up a loop tiling pass helper (NFC)

PiperOrigin-RevId: 223422077

5 years ago[MLIR] Reenable materialize_vectors test
Nicolas Vasilache [Thu, 29 Nov 2018 21:34:47 +0000 (13:34 -0800)]
[MLIR] Reenable materialize_vectors test

Fixes one of the Filecheck'ed test which was mistakenly disabled.

PiperOrigin-RevId: 223401978

5 years agoAdd support for result type iteration in Operation/Instruction/OperationStmt.
River Riddle [Thu, 29 Nov 2018 01:23:16 +0000 (17:23 -0800)]
Add support for result type iteration in Operation/Instruction/OperationStmt.

PiperOrigin-RevId: 223264992

5 years agoSplit "rewrite" functionality out of Pattern into a new RewritePattern derived
Chris Lattner [Wed, 28 Nov 2018 23:09:39 +0000 (15:09 -0800)]
Split "rewrite" functionality out of Pattern into a new RewritePattern derived
class.  This change is NFC, but allows for new kinds of patterns, specifically
LegalizationPatterns which will be allowed to change the types of things they
rewrite.

PiperOrigin-RevId: 223243783

5 years agoVerify CmpIOp's result type to be bool-like
Lei Zhang [Wed, 28 Nov 2018 19:49:26 +0000 (11:49 -0800)]
Verify CmpIOp's result type to be bool-like

This CL added two new traits, SameOperandsAndResultShape and
ResultsAreBoolLike, and changed CmpIOp to embody these two
traits. As a consequence, CmpIOp's result type now is verified
to be bool-like.

PiperOrigin-RevId: 223208438

5 years agoAdd derived attribute support.
Jacques Pienaar [Wed, 28 Nov 2018 17:21:42 +0000 (09:21 -0800)]
Add derived attribute support.

Derived attributes are attributes that are derived from other properties of the operation (e.g., the shape returned from the type). DerivedAttr is parameterized on the return type and function body.

PiperOrigin-RevId: 223180315

5 years agoStandardOps: introduce 'select'.
Alex Zinenko [Wed, 28 Nov 2018 15:08:55 +0000 (07:08 -0800)]
StandardOps: introduce 'select'.

The semantics of 'select' is conventional: return the second operand if the
first operand is true (1 : i1) and the third operand otherwise.  It is
applicable to vectors and tensors element-wise, similarly to LLVM instruction.
This operation is necessary to implement min/max to lower 'for' loops with
complex bounds to CFG functions and to support ternary operations in ML
functions.  It is preferred to first-class min/max because of its simplicity,
e.g. it is not concered with signedness.

PiperOrigin-RevId: 223160860

5 years agoLLVM IR lowering: support 'dim' operation.
Alex Zinenko [Wed, 28 Nov 2018 15:07:56 +0000 (07:07 -0800)]
LLVM IR lowering: support 'dim' operation.

Add support for translating 'dim' opreation on MemRefs to LLVM IR.  For a
static size, this operation merely defines an LLVM IR constant value that may
not appear in the output IR if not used (and had not been removed before by
DCE).  For a dynamic size, this operation is translated into an access to the
MemRef descriptor that contains the dynamic size.

PiperOrigin-RevId: 223160774

5 years agoLLVM IR lowering: support simple MemRef types
Alex Zinenko [Wed, 28 Nov 2018 10:32:10 +0000 (02:32 -0800)]
LLVM IR lowering: support simple MemRef types

Introduce initial support for MemRef types, including type conversion,
allocation and deallocation, read and write element-wise access, passing
MemRefs to and returning from functions.  Affine map compositions and
non-default memory spaces are NOT YET supported.

Lowered code needs to handle potentially dynamic sizes of the MemRef.  To do
so, it replaces a MemRef-typed value with a special MemRef descriptor that
carries the data and the dynamic sizes together.  A MemRef type is converted to
LLVM's first-class structure type with the first element being the pointer to
the data buffer with data layed out linearly, followed by as many integer-typed
elements as MemRef has dynamic sizes.  The type of these elements is that of
MLIR index lowered to LLVM.  For example, `memref<?x42x?xf32>` is converted to
`{ f32*, i64, i64 }` provided `index` is lowered to `i64`.  While it is
possible to convert MemRefs with fully static sizes to simple pointers to their
elemental types, we opted for consistency and convert them to the
single-element structure.  This makes the conversion code simpler and the
calling convention of the generated LLVM IR functions consistent.

Loads from and stores to a MemRef element are lowered to a sequence of LLVM
instructions that, first, computes the linearized index of the element in the
data buffer using the access indices and combining the static sizes with the
dynamic sizes stored in the descriptor, and then loads from or stores to the
buffer element indexed by the linearized subscript.  While some of the index
computations may be redundant (i.e., consecutive load and store to the same
location in the same scope could reuse the linearized index), we emit them for
every operation.  A subsequent optimization pass may eliminate them if
necessary.

MemRef allocation and deallocation is performed using external functions
`__mlir_alloc(index) -> i8*` and `__mlir_free(i8*)` that must be implemented by
the caller.  These functions behave similarly to `malloc` and `free`, but can
be extended to support different memory spaces in future.  Allocation and
deallocation instructions take care of casting the pointers.  Prior to calling
the allocation function, the emitted code creates an SSA Value for the
descriptor and uses it to store the dynamic sizes of the MemRef passed to the
allocation operation.  It further emits instructions that compute the dynamic
amount of memory to allocate in bytes.  Finally, the allocation stores the
result of calling the `__mlir_alloc` in the MemRef descriptor.  Deallocation
extracts the pointer to the allocated memory from the descriptor and calls
`__mlir_free` on it.  The descriptor itself is not modified and, being
stack-allocated, ceases to exist when it goes out of scope.

MLIR functions that access MemRef values as arguments or return them are
converted to LLVM IR functions that accept MemRef descriptors as LLVM IR
structure types by value.  This significantly simplifies the calling convention
at the LLVM IR level and avoids handling descriptors in the dynamic memory,
however is not always comaptible with LLVM IR functions emitted from C code
with similar signatures.  A separate LLVM pass may be introduced in the future
to provide C-compatible calling conventions for LLVM IR functions generated
from MLIR.

PiperOrigin-RevId: 223134883

5 years agoMake operation names hashable.
River Riddle [Wed, 28 Nov 2018 04:32:31 +0000 (20:32 -0800)]
Make operation names hashable.

PiperOrigin-RevId: 223104253

5 years agoCreate Passes.md.
Alex Zinenko [Wed, 28 Nov 2018 00:15:29 +0000 (16:15 -0800)]
Create Passes.md.

Start the documentation file listing available MLIR passes.  Briefly describe
the `-convert-to-cfg` and the `-lower-affine-apply` passes.  These passes
serve as description templates for other passes.  In particular, they include
the dialect and operation restrictions in the pass input and output.

PiperOrigin-RevId: 223076894

5 years agoFix typo.
Jacques Pienaar [Tue, 27 Nov 2018 22:49:21 +0000 (14:49 -0800)]
Fix typo.

Tensor has as element type a tensor-memref-element-type rather than a vector-element-type.

PiperOrigin-RevId: 223062135

5 years agoConvert tf.FusedBatchNorm into tfl primary math ops
Lei Zhang [Tue, 27 Nov 2018 19:35:19 +0000 (11:35 -0800)]
Convert tf.FusedBatchNorm into tfl primary math ops

* Added TF::FusedBatchNormOp
* Validated TF::FusedBatchNormOp's operands
* Added converter from tf.FusedBatchNorm to tfl math ops

In the converter, we additionally check that the 'is_training'
attribute in tf.FusedBatchNorm is false and the last 4 outputs
are all not used (true for inference). These requirements do
not exist in the original TOCO source code, which just silently
ignores the last 4 outputs.

PiperOrigin-RevId: 223027333

5 years agoAdd support for setting the location of an IROperandOwner.
River Riddle [Tue, 27 Nov 2018 16:33:49 +0000 (08:33 -0800)]
Add support for setting the location of an IROperandOwner.

PiperOrigin-RevId: 222995814

5 years agoTidy up the replaceOp hooks in PatternMatch, generalizing them to support any
Chris Lattner [Sat, 24 Nov 2018 15:40:55 +0000 (07:40 -0800)]
Tidy up the replaceOp hooks in PatternMatch, generalizing them to support any
number of result ops.  Among other things, this results in shorter names

PiperOrigin-RevId: 222685039

5 years agoMinimal patch to allow patterns to rewrite multi-result instructions, related to...
Chris Lattner [Fri, 23 Nov 2018 09:10:26 +0000 (01:10 -0800)]
Minimal patch to allow patterns to rewrite multi-result instructions, related to b/119877155

PiperOrigin-RevId: 222597798

5 years agoRename Deaffinator to LowerAffineApply and patch it.
Alex Zinenko [Thu, 22 Nov 2018 19:09:26 +0000 (11:09 -0800)]
Rename Deaffinator to LowerAffineApply and patch it.

Several things were suggested in post-submission reviews.  In particular, use
pointers in function interfaces instead of references (still use references
internally).  Clarify the behavior of the pass in presence of MLFunctions.

PiperOrigin-RevId: 222556851

5 years ago[MLIR] Fix opt build
Nicolas Vasilache [Thu, 22 Nov 2018 04:10:10 +0000 (20:10 -0800)]
[MLIR] Fix opt build

PiperOrigin-RevId: 222491353

5 years ago[MLIR][MaterializeVectors] Add a MaterializeVector pass via unrolling.
Nicolas Vasilache [Wed, 21 Nov 2018 21:46:54 +0000 (13:46 -0800)]
[MLIR][MaterializeVectors] Add a MaterializeVector pass via unrolling.

This CL adds an MLIR-MLIR pass which materializes super-vectors to
hardware-dependent sized vectors.

While the physical vector size is target-dependent, the pass is written in
a target-independent way: the target vector size is specified as a parameter
to the pass. This pass is thus a partial lowering that opens the "greybox"
that is the super-vector abstraction.

This first CL adds a first materilization pass iterates over vector_transfer_write operations and:
1. computes the program slice including the current vector_transfer_write;
2. computes the multi-dimensional ratio of super-vector shape to hardware
vector shape;
3. for each possible multi-dimensional value within the bounds of ratio, a new slice is
instantiated (i.e. cloned and rewritten) so that all operations in this instance operate on
the hardware vector type.

As a simple example, given:
```mlir
mlfunc @vector_add_2d(%M : index, %N : index) -> memref<?x?xf32> {
  %A = alloc (%M, %N) : memref<?x?xf32>
  %B = alloc (%M, %N) : memref<?x?xf32>
  %C = alloc (%M, %N) : memref<?x?xf32>
  for %i0 = 0 to %M {
    for %i1 = 0 to %N {
      %a1 = load %A[%i0, %i1] : memref<?x?xf32>
      %b1 = load %B[%i0, %i1] : memref<?x?xf32>
      %s1 = addf %a1, %b1 : f32
      store %s1, %C[%i0, %i1] : memref<?x?xf32>
    }
  }
  return %C : memref<?x?xf32>
}
```

and the following options:
```
-vectorize -virtual-vector-size 32 --test-fastest-varying=0 -materialize-vectors -vector-size=8
```

materialization emits:
```mlir
#map0 = (d0, d1) -> (d0, d1)
#map1 = (d0, d1) -> (d0, d1 + 8)
#map2 = (d0, d1) -> (d0, d1 + 16)
#map3 = (d0, d1) -> (d0, d1 + 24)
mlfunc @vector_add_2d(%arg0 : index, %arg1 : index) -> memref<?x?xf32> {
  %0 = alloc(%arg0, %arg1) : memref<?x?xf32>
  %1 = alloc(%arg0, %arg1) : memref<?x?xf32>
  %2 = alloc(%arg0, %arg1) : memref<?x?xf32>
  for %i0 = 0 to %arg0 {
    for %i1 = 0 to %arg1 step 32 {
      %3 = affine_apply #map0(%i0, %i1)
      %4 = "vector_transfer_read"(%0, %3tensorflow/mlir#0, %3tensorflow/mlir#1) : (memref<?x?xf32>, index, index) -> vector<8xf32>
      %5 = affine_apply #map1(%i0, %i1)
      %6 = "vector_transfer_read"(%0, %5tensorflow/mlir#0, %5tensorflow/mlir#1) : (memref<?x?xf32>, index, index) -> vector<8xf32>
      %7 = affine_apply #map2(%i0, %i1)
      %8 = "vector_transfer_read"(%0, %7tensorflow/mlir#0, %7tensorflow/mlir#1) : (memref<?x?xf32>, index, index) -> vector<8xf32>
      %9 = affine_apply #map3(%i0, %i1)
      %10 = "vector_transfer_read"(%0, %9tensorflow/mlir#0, %9tensorflow/mlir#1) : (memref<?x?xf32>, index, index) -> vector<8xf32>
      %11 = affine_apply #map0(%i0, %i1)
      %12 = "vector_transfer_read"(%1, %11tensorflow/mlir#0, %11tensorflow/mlir#1) : (memref<?x?xf32>, index, index) -> vector<8xf32>
      %13 = affine_apply #map1(%i0, %i1)
      %14 = "vector_transfer_read"(%1, %13tensorflow/mlir#0, %13tensorflow/mlir#1) : (memref<?x?xf32>, index, index) -> vector<8xf32>
      %15 = affine_apply #map2(%i0, %i1)
      %16 = "vector_transfer_read"(%1, %15tensorflow/mlir#0, %15tensorflow/mlir#1) : (memref<?x?xf32>, index, index) -> vector<8xf32>
      %17 = affine_apply #map3(%i0, %i1)
      %18 = "vector_transfer_read"(%1, %17tensorflow/mlir#0, %17tensorflow/mlir#1) : (memref<?x?xf32>, index, index) -> vector<8xf32>
      %19 = addf %4, %12 : vector<8xf32>
      %20 = addf %6, %14 : vector<8xf32>
      %21 = addf %8, %16 : vector<8xf32>
      %22 = addf %10, %18 : vector<8xf32>
      %23 = affine_apply #map0(%i0, %i1)
      "vector_transfer_write"(%19, %2, %23tensorflow/mlir#0, %23tensorflow/mlir#1) : (vector<8xf32>, memref<?x?xf32>, index, index) -> ()
      %24 = affine_apply #map1(%i0, %i1)
      "vector_transfer_write"(%20, %2, %24tensorflow/mlir#0, %24tensorflow/mlir#1) : (vector<8xf32>, memref<?x?xf32>, index, index) -> ()
      %25 = affine_apply #map2(%i0, %i1)
      "vector_transfer_write"(%21, %2, %25tensorflow/mlir#0, %25tensorflow/mlir#1) : (vector<8xf32>, memref<?x?xf32>, index, index) -> ()
      %26 = affine_apply #map3(%i0, %i1)
      "vector_transfer_write"(%22, %2, %26tensorflow/mlir#0, %26tensorflow/mlir#1) : (vector<8xf32>, memref<?x?xf32>, index, index) -> ()
    }
  }
  return %2 : memref<?x?xf32>
}
```

PiperOrigin-RevId: 222455351

5 years ago[MLIR][Slicing] Apply cleanups
Nicolas Vasilache [Wed, 21 Nov 2018 21:41:59 +0000 (13:41 -0800)]
[MLIR][Slicing] Apply cleanups

This CL applies a few last cleanups from a previous CL that have been
missed during the previous submit.

PiperOrigin-RevId: 222454774

5 years ago[MLIR][Slicing] Add utils for computing slices.
Nicolas Vasilache [Wed, 21 Nov 2018 20:34:10 +0000 (12:34 -0800)]
[MLIR][Slicing] Add utils for computing slices.

This CL adds tooling for computing slices as an independent CL.
The first consumer of this analysis will be super-vector materialization in a
followup CL.

In particular, this adds:
1. a getForwardStaticSlice function with documentation, example and a
standalone unit test;
2. a getBackwardStaticSlice function with documentation, example and a
standalone unit test;
3. a getStaticSlice function with documentation, example and a standalone unit
test;
4. a topologicalSort function that is exercised through the getStaticSlice
unit test.

The getXXXStaticSlice functions take an additional root (resp. terminators)
parameter which acts as a boundary that the transitive propagation algorithm
is not allowed to cross.

PiperOrigin-RevId: 222446208

5 years agoClean up parse_headers in mlir
MLIR Team [Wed, 21 Nov 2018 19:53:12 +0000 (11:53 -0800)]
Clean up parse_headers in mlir

Not having self-contained headers in LLVM is a constant pain. Don't make the
same mistake in mlir. The only interesting change here is moving setSuccessor
to Instructions.cpp, which breaks the cycle between Instructions.h and
BasicBlock.h.

PiperOrigin-RevId: 222440816

5 years agoFix bugs in DMA generation and FlatAffineConstraints; add more test
Uday Bondhugula [Wed, 21 Nov 2018 19:12:05 +0000 (11:12 -0800)]
Fix bugs in DMA generation and FlatAffineConstraints; add more test
cases.

- fix bug in calculating index expressions for DMA buffers in certain cases
  (affected tiled loop nests); add more test cases for better coverage.
- introduce an additional optional argument to replaceAllMemRefUsesWith;
  additional operands to the index remap AffineMap can now be supplied by the
  client.
- FlatAffineConstraints::addBoundsForStmt - fix off by one upper bound,
  ::composeMap - fix position bug.
- Some clean up and more comments

PiperOrigin-RevId: 222434628

5 years agoIntroduce Deaffinator pass.
Alex Zinenko [Wed, 21 Nov 2018 15:42:16 +0000 (07:42 -0800)]
Introduce Deaffinator pass.

This function pass replaces affine_apply operations in CFG functions with
sequences of primitive arithmetic instructions that form the affine map.

The actual replacement functionality is located in LoweringUtils as a
standalone function operating on an individual affine_apply operation and
inserting the result at the location of the original operation.  It is expected
to be useful for other, target-specific lowering passes that may start at
MLFunction level that Deaffinator does not support.

PiperOrigin-RevId: 222406692

5 years agoLower scalar parts of CFG functions to LLVM IR
Alex Zinenko [Wed, 21 Nov 2018 14:37:49 +0000 (06:37 -0800)]
Lower scalar parts of CFG functions to LLVM IR

Initial restricted implementaiton of the MLIR to LLVM IR translation.
Introduce a new flow into the mlir-translate tool taking an MLIR module
containing CFG functions only and producing and LLVM IR module.  The MLIR
features supported by the translator are as follows:
- primitive and function types;
- integer constants;
- cfg and ext functions with 0 or 1 return values;
- calls to these functions;
- basic block conversion translation of arguments to phi nodes;
- conversion between arguments of the first basic block and function arguments;
- (conditional) branches;
- integer addition and comparison operations.

Are NOT supported:
- vector and tensor types and operations on them;
- memrefs and operations on them;
- allocations;
- functions returning multiple values;
- LLVM Module triple and data layout (index type is hardcoded to i64).

Create a new MLIR library and place it under lib/Target/LLVMIR.  The "Target"
library group is similar to the one present in LLVM and is intended to contain
all future public MLIR translation targets.

The general flow of MLIR to LLVM IR convresion will include several lowering
and simplification passes on the MLIR itself in order to make the translation
as simple as possible.  In particular, ML functions should be transformed to
CFG functions by the recently introduced pass, operations on structured types
will be converted to sequences of operations on primitive types, complex
operations such as affine_apply will be converted into sequence of primitive
operations, primitive operations themselves may eventually be converted to an
LLVM dialect that uses LLVM-like operations.

Introduce the first translation test so that further changes make sure the
basic translation functionality is not broken.

PiperOrigin-RevId: 222400112

5 years agoCreate the Support library.
Alex Zinenko [Wed, 21 Nov 2018 14:24:20 +0000 (06:24 -0800)]
Create the Support library.

This has been a long-standing TODO in the build system.  Now that we need to
share the non-inlined implementation of file utilities for translators, create
a separate library for support functionality.  Move Support/* headers to the
new library in the build system.

PiperOrigin-RevId: 222398880

5 years agoSeparate translators into "from MLIR" and "to MLIR".
Alex Zinenko [Wed, 21 Nov 2018 14:22:17 +0000 (06:22 -0800)]
Separate translators into "from MLIR" and "to MLIR".

Translations performed by mlir-translate only have MLIR on one end.
MLIR-to-MLIR conversions (including dialect changes) should be treated as
passes and run by mlir-opt.  Individual translations should not care about
reading or writing MLIR and should work on in-memory representation of MLIR
modules instead.  Split the TranslateFunction interface and the translate
registry into two parts: "from MLIR" and "to MLIR".

Update mlir-translate to handle both registries together by wrapping
translation functions into source-to-source convresions.  Remove MLIR parsing
and writing from individual translations and make them operate on Modules
instead.  This removes the need for individual translators to include
tools/mlir-translate/mlir-translate.h, which can now be safely removed.

Remove mlir-to-mlir translation that only existed as a registration example and
use mlir-opt instead for tests.

PiperOrigin-RevId: 222398707

5 years agoFactor out translation registry.
Alex Zinenko [Wed, 21 Nov 2018 14:21:19 +0000 (06:21 -0800)]
Factor out translation registry.

The mlir-translate tool is expected to discover individual translations at link
time.  These translations must register themselves and may need the utilities
that are currently defined in mlir-translate.cpp for their entry point
functions.  Since mlir-translate is linking against individual translations,
the translations cannot link against mlir-translate themselves.  Extract out
the utilities into a separate "Translation" library to avoid the potential
dependency cycle.  Individual translations link to that library to access
TranslateRegistration. The mlir-translate tool links to individual translations
and to the "Translation" library because it needs the utilities as well.

The main header of the new library is located in include/mlir/Translation.h to
make it easily accessible by translators.  The rationale for putting it to
include/mlir rather than to one of its subdirectories is that its purpose is
similar to that of include/mlir/Pass.h so it makes sense to put them at the
same level.

PiperOrigin-RevId: 222398617

5 years agoIntroduce TF WhileOp and lower it to MLIR CFG
Smit Hinsu [Wed, 21 Nov 2018 02:43:22 +0000 (18:43 -0800)]
Introduce TF WhileOp and lower it to MLIR CFG

Also, added iterators for VariadicResults class.

TESTED with unit tests

TODOs:
- Handle non-bool condition results (similar to the IfOp)
- Use PatternRewriter
PiperOrigin-RevId: 222340376

5 years agoAdd verifier check for integer constants to check that the value can fit within the...
River Riddle [Wed, 21 Nov 2018 01:51:07 +0000 (17:51 -0800)]
Add verifier check for integer constants to check that the value can fit within the type bit width.

PiperOrigin-RevId: 222335526

5 years agoRemove unnecessary include from StandardOps.cpp.
River Riddle [Tue, 20 Nov 2018 23:27:44 +0000 (15:27 -0800)]
Remove unnecessary include from StandardOps.cpp.

PiperOrigin-RevId: 222316745

5 years agoRemove allocations for memref's that become dead as a result of double
Uday Bondhugula [Tue, 20 Nov 2018 23:07:37 +0000 (15:07 -0800)]
Remove allocations for memref's that become dead as a result of double
buffering in the auto DMA overlap pass.

This is done online in the pass.

PiperOrigin-RevId: 222313640

5 years agoAdd iterators and size() helper method in ArrayAttr
Lei Zhang [Tue, 20 Nov 2018 23:00:51 +0000 (15:00 -0800)]
Add iterators and size() helper method in ArrayAttr

PiperOrigin-RevId: 222312276

5 years agoAffineExprVisitor: fix names of default visitation functions.
Alex Zinenko [Tue, 20 Nov 2018 22:59:54 +0000 (14:59 -0800)]
AffineExprVisitor: fix names of default visitation functions.

Existing default visitation function for dimension and symbols were called
"visitAffineDimExpr" and "visitAffineSymbolExpr".  However, generic CRTP-based
visit and walk methods were calling "visitDimExpr" and "visitSymbolExpr",
respectively, on derived classes.  This has not been discovered before because
all existing affine expression visitors (re)define functions for dimensions and
symbols.  Change the names of the default empty visitation functions to the
latter form.

PiperOrigin-RevId: 222312114

5 years agoAdds ConstantFoldHook registry in MLIRContext
Feng Liu [Tue, 20 Nov 2018 22:47:10 +0000 (14:47 -0800)]
Adds ConstantFoldHook registry in MLIRContext

This reverts the previous method which needs to create a new dialect with the
constant fold hook from TensorFlow. This new method uses a function object in
dialect to store the constant fold hook. Once a hook is registered to the
dialect, this function object will be assigned when the dialect is added to the
MLIRContext.

For the operations which are not registered, a new method getRegisteredDialects
is added to the MLIRContext to query the dialects which matches their op name
prefixes.

PiperOrigin-RevId: 222310149

5 years agoAdd functionality for erasing terminator successor operands and basic block arguments.
River Riddle [Tue, 20 Nov 2018 22:03:41 +0000 (14:03 -0800)]
Add functionality for erasing terminator successor operands and basic block arguments.

PiperOrigin-RevId: 222303233

5 years ago Automated rollback of changelist 221863955.
Uday Bondhugula [Tue, 20 Nov 2018 21:39:35 +0000 (13:39 -0800)]
Automated rollback of changelist 221863955.

PiperOrigin-RevId: 222299120

5 years ago[MLIR][Vectorize] Refactor Vectorize use-def propagation.
Nicolas Vasilache [Tue, 20 Nov 2018 19:39:32 +0000 (11:39 -0800)]
[MLIR][Vectorize] Refactor Vectorize use-def propagation.

This CL refactors a few things in Vectorize.cpp:
1. a clear distinction is made between:
  a. the LoadOp are the roots of vectorization and must be vectorized
  eagerly and propagate their value; and
  b. the StoreOp which are the terminals of vectorization and must be
  vectorized late (i.e. they do not produce values that need to be
  propagated).
2. the StoreOp must be vectorized late because in general it can store a value
that is not reachable from the subset of loads defined in the
current pattern. One trivial such case is storing a constant defined at the
top-level of the MLFunction and that needs to be turned into a splat.
3. a description of the algorithm is given;
4. the implementation matches the algorithm;
5. the last example is made parametric, in practice it will fully rely on the
implementation of vector_transfer_read/write which will handle boundary
conditions and padding. This will happen by lowering to a lower-level
abstraction either:
  a. directly in MLIR (whether DMA or just loops or any async tasks in the
     future) (whiteboxing);
  b. in LLO/LLVM-IR/whatever blackbox library call/ search + swizzle inventor
  one may want to use;
  c. a partial mix of a. and b. (grey-boxing)
5. minor cleanups are applied;
6. mistakenly disabled unit tests are re-enabled (oopsie).

With this CL, this MLIR snippet:
```
mlfunc @vector_add_2d(%M : index, %N : index) -> memref<?x?xf32> {
  %A = alloc (%M, %N) : memref<?x?xf32>
  %B = alloc (%M, %N) : memref<?x?xf32>
  %C = alloc (%M, %N) : memref<?x?xf32>
  %f1 = constant 1.0 : f32
  %f2 = constant 2.0 : f32
  for %i0 = 0 to %M {
    for %i1 = 0 to %N {
      // non-scoped %f1
      store %f1, %A[%i0, %i1] : memref<?x?xf32>
    }
  }
  for %i4 = 0 to %M {
    for %i5 = 0 to %N {
      %a5 = load %A[%i4, %i5] : memref<?x?xf32>
      %b5 = load %B[%i4, %i5] : memref<?x?xf32>
      %s5 = addf %a5, %b5 : f32
      // non-scoped %f1
      %s6 = addf %s5, %f1 : f32
      store %s6, %C[%i4, %i5] : memref<?x?xf32>
    }
  }
  return %C : memref<?x?xf32>
}
```

vectorized with these arguments:
```
-vectorize -virtual-vector-size 256 --test-fastest-varying=0
```

vectorization produces this standard innermost-loop vectorized code:
```
mlfunc @vector_add_2d(%arg0 : index, %arg1 : index) -> memref<?x?xf32> {
  %0 = alloc(%arg0, %arg1) : memref<?x?xf32>
  %1 = alloc(%arg0, %arg1) : memref<?x?xf32>
  %2 = alloc(%arg0, %arg1) : memref<?x?xf32>
  %cst = constant 1.000000e+00 : f32
  %cst_0 = constant 2.000000e+00 : f32
  for %i0 = 0 to %arg0 {
    for %i1 = 0 to %arg1 step 256 {
      %cst_1 = constant splat<vector<256xf32>, 1.000000e+00> : vector<256xf32>
      "vector_transfer_write"(%cst_1, %0, %i0, %i1) : (vector<256xf32>, memref<?x?xf32>, index, index) -> ()
    }
  }
  for %i2 = 0 to %arg0 {
    for %i3 = 0 to %arg1 step 256 {
      %3 = "vector_transfer_read"(%0, %i2, %i3) : (memref<?x?xf32>, index, index) -> vector<256xf32>
      %4 = "vector_transfer_read"(%1, %i2, %i3) : (memref<?x?xf32>, index, index) -> vector<256xf32>
      %5 = addf %3, %4 : vector<256xf32>
      %cst_2 = constant splat<vector<256xf32>, 1.000000e+00> : vector<256xf32>
      %6 = addf %5, %cst_2 : vector<256xf32>
      "vector_transfer_write"(%6, %2, %i2, %i3) : (vector<256xf32>, memref<?x?xf32>, index, index) -> ()
    }
  }
  return %2 : memref<?x?xf32>
}
```

Of course, much more intricate n-D imperfectly-nested patterns can be emitted too in a fully declarative fashion, but this is enough for now.

PiperOrigin-RevId: 222280209

5 years agoConvert TF::Conv2D into TFL::Conv2D
Lei Zhang [Tue, 20 Nov 2018 19:25:05 +0000 (11:25 -0800)]
Convert TF::Conv2D into TFL::Conv2D

Added TF::Conv2D op and TFL::Conv2D op, and converted TF::Conv2D to
TFL::Conv2D, which need to address the operand numberr mismatch
and attribute conversion.
PiperOrigin-RevId: 222277554

5 years agoConvertToCFG: handle loop 1D affine loop bounds.
Alex Zinenko [Tue, 20 Nov 2018 19:15:03 +0000 (11:15 -0800)]
ConvertToCFG: handle loop 1D affine loop bounds.

In the general case, loop bounds can be expressed as affine maps of the outer
loop iterators and function arguments.  Relax the check for loop bounds to be
known integer constants and also accept one-dimensional affine bounds in
ConvertToCFG ForStmt lowering.  Emit affine_apply operations for both the upper
and the lower bound.  The semantics of MLFunctions guarantees that both bounds
can be computed before the loop starts iterating.  Constant bounds are merely a
short-hand notation for zero-dimensional affine maps and get supported
transparently.

Multidimensional affine bounds are not yet supported because the target IR
dialect lacks min/max operations necessary to implement the corresponding
semantics.

PiperOrigin-RevId: 222275801

5 years agoAdd support for getting the operand number from an IROperandImpl(InstOperand, BasicBl...
River Riddle [Tue, 20 Nov 2018 19:07:58 +0000 (11:07 -0800)]
Add support for getting the operand number from an IROperandImpl(InstOperand, BasicBlockOperand, StmtOperand).

PiperOrigin-RevId: 222274598

5 years agoAdd op stats pass to mlir-opt.
Jacques Pienaar [Tue, 20 Nov 2018 17:38:15 +0000 (09:38 -0800)]
Add op stats pass to mlir-opt.

op-stats pass currently returns the number of occurrences of different operations in a Module. Useful for verifying transformation properties (e.g., 3 ops of specific dialect, 0 of another), but probably not useful outside of that so keeping it local to mlir-opt. This does not consider op attributes when counting.

PiperOrigin-RevId: 222259727

5 years agoAdd support for Operation::moveBefore(Operation *).
River Riddle [Tue, 20 Nov 2018 16:48:08 +0000 (08:48 -0800)]
Add support for Operation::moveBefore(Operation *).

PiperOrigin-RevId: 222252521

5 years ago[MLIR][VectorAnalysis] Add a VectorAnalysis and standalone tests
Nicolas Vasilache [Tue, 20 Nov 2018 16:36:07 +0000 (08:36 -0800)]
[MLIR][VectorAnalysis] Add a VectorAnalysis and standalone tests

This CL adds some vector support in prevision of the upcoming vector
materialization pass. In particular this CL adds 2 functions to:
1. compute the multiplicity of a subvector shape in a supervector shape;
2. help match operations on strict super-vectors. This is defined for a given
subvector shape as an operation that manipulates a vector type that is an
integral multiple of the subtype, with multiplicity at least 2.

This CL also adds a TestUtil pass where we can dump arbitrary testing of
functions and analysis that operate at a much smaller granularity than a pass
(e.g. an analysis for which it is convenient to write a bit of artificial MLIR
and write some custom test). This is in order to keep using Filecheck for
things that essentially look and feel like C++ unit tests.

PiperOrigin-RevId: 222250910

5 years agoConvert MLIR DiagnosticKind to LLVM DiagKind when emitting diagnostic via mlir-opt.
Jacques Pienaar [Mon, 19 Nov 2018 23:15:36 +0000 (15:15 -0800)]
Convert MLIR DiagnosticKind to LLVM DiagKind when emitting diagnostic via mlir-opt.

PiperOrigin-RevId: 222147297

5 years agoUpdate 'return' statement syntax in LangRef to reflect the actual parsing syntax.
River Riddle [Mon, 19 Nov 2018 19:21:59 +0000 (11:21 -0800)]
Update 'return' statement syntax in LangRef to reflect the actual parsing syntax.

PiperOrigin-RevId: 222107722

5 years agoFix the implementation of PatternRewriter::createChecked. The current implementation...
River Riddle [Mon, 19 Nov 2018 04:04:51 +0000 (20:04 -0800)]
Fix the implementation of PatternRewriter::createChecked. The current implementation has bit rotted and won't compile. This cl updates the implementation to be similar to (CFGFuncBuilder/MLFuncBuilder)::createChecked.

PiperOrigin-RevId: 222014317