1//===-- TestOps.td - Test dialect operation definitions ----*- tablegen -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#ifndef TEST_OPS
10#define TEST_OPS
11
12include "mlir/IR/OpBase.td"
13include "mlir/IR/OpAsmInterface.td"
14include "mlir/IR/RegionKindInterface.td"
15include "mlir/IR/SymbolInterfaces.td"
16include "mlir/Interfaces/CallInterfaces.td"
17include "mlir/Interfaces/ControlFlowInterfaces.td"
18include "mlir/Interfaces/CopyOpInterface.td"
19include "mlir/Interfaces/InferTypeOpInterface.td"
20include "mlir/Interfaces/SideEffectInterfaces.td"
21include "TestInterfaces.td"
22
23def Test_Dialect : Dialect {
24  let name = "test";
25  let cppNamespace = "::mlir::test";
26  let hasConstantMaterializer = 1;
27  let hasOperationAttrVerify = 1;
28  let hasRegionArgAttrVerify = 1;
29  let hasRegionResultAttrVerify = 1;
30}
31
32class TEST_Op<string mnemonic, list<OpTrait> traits = []> :
33    Op<Test_Dialect, mnemonic, traits>;
34
35//===----------------------------------------------------------------------===//
36// Test Types
37//===----------------------------------------------------------------------===//
38
39def IntTypesOp : TEST_Op<"int_types"> {
40  let results = (outs
41    AnyI16:$any_i16,
42    SI32:$si32,
43    UI64:$ui64,
44    AnyInteger:$any_int
45  );
46}
47
48def ComplexF64 : Complex<F64>;
49def ComplexOp : TEST_Op<"complex_f64"> {
50  let results = (outs ComplexF64);
51}
52
53def ComplexTensorOp : TEST_Op<"complex_f64_tensor"> {
54  let results = (outs TensorOf<[ComplexF64]>);
55}
56
57def TupleOp : TEST_Op<"tuple_32_bit"> {
58  let results = (outs TupleOf<[I32, F32]>);
59}
60
61def NestedTupleOp : TEST_Op<"nested_tuple_32_bit"> {
62  let results = (outs NestedTupleOf<[I32, F32]>);
63}
64
65def TakesStaticMemRefOp : TEST_Op<"takes_static_memref"> {
66  let arguments = (ins AnyStaticShapeMemRef:$x);
67}
68
69def RankLessThan2I8F32MemRefOp : TEST_Op<"rank_less_than_2_I8_F32_memref"> {
70  let results = (outs MemRefRankOf<[I8, F32], [0, 1]>);
71}
72
73def NDTensorOfOp : TEST_Op<"nd_tensor_of"> {
74  let arguments = (ins
75    0DTensorOf<[F32]>:$arg0,
76    1DTensorOf<[F32]>:$arg1,
77    2DTensorOf<[I16]>:$arg2,
78    3DTensorOf<[I16]>:$arg3,
79    4DTensorOf<[I16]>:$arg4
80  );
81}
82
83def RankedTensorOp : TEST_Op<"ranked_tensor_op"> {
84  let arguments = (ins AnyRankedTensor:$input);
85}
86
87def MultiTensorRankOf : TEST_Op<"multi_tensor_rank_of"> {
88  let arguments = (ins
89    TensorRankOf<[I8, I32, F32], [0, 1]>:$arg0
90  );
91}
92
93def TEST_TestType : DialectType<Test_Dialect,
94    CPred<"$_self.isa<::mlir::test::TestType>()">, "test">,
95    BuildableType<"$_builder.getType<::mlir::test::TestType>()">;
96
97//===----------------------------------------------------------------------===//
98// Test Symbols
99//===----------------------------------------------------------------------===//
100
101def SymbolOp : TEST_Op<"symbol", [Symbol]> {
102  let summary =  "operation which defines a new symbol";
103  let arguments = (ins StrAttr:$sym_name,
104                       OptionalAttr<StrAttr>:$sym_visibility);
105}
106
107def SymbolScopeOp : TEST_Op<"symbol_scope",
108    [SymbolTable, SingleBlockImplicitTerminator<"TerminatorOp">]> {
109  let summary =  "operation which defines a new symbol table";
110  let regions = (region SizedRegion<1>:$region);
111}
112
113def SymbolTableRegionOp : TEST_Op<"symbol_table_region", [SymbolTable]> {
114  let summary =  "operation which defines a new symbol table without a "
115                 "restriction on a terminator";
116  let regions = (region SizedRegion<1>:$region);
117}
118
119//===----------------------------------------------------------------------===//
120// Test Operands
121//===----------------------------------------------------------------------===//
122
123def MixedNormalVariadicOperandOp : TEST_Op<
124    "mixed_normal_variadic_operand", [SameVariadicOperandSize]> {
125  let arguments = (ins
126    Variadic<AnyTensor>:$input1,
127    AnyTensor:$input2,
128    Variadic<AnyTensor>:$input3
129  );
130}
131def VariadicWithSameOperandsResult :
132      TEST_Op<"variadic_with_same_operand_results",
133              [SameOperandsAndResultType]> {
134  let arguments = (ins Variadic<AnySignlessInteger>:$operands);
135  let results = (outs AnySignlessInteger:$result);
136}
137
138def SameOperandsResultType : TEST_Op<
139    "same_operand_result_type", [SameOperandsAndResultType]> {
140  let arguments = (ins AnyTensor:$operand);
141  let results = (outs AnyTensor:$result);
142}
143
144//===----------------------------------------------------------------------===//
145// Test Results
146//===----------------------------------------------------------------------===//
147
148def MixedNormalVariadicResults : TEST_Op<
149    "mixed_normal_variadic_result", [SameVariadicResultSize]> {
150  let results = (outs
151    Variadic<AnyTensor>:$output1,
152    AnyTensor:$output2,
153    Variadic<AnyTensor>:$output3
154  );
155}
156
157//===----------------------------------------------------------------------===//
158// Test Attributes
159//===----------------------------------------------------------------------===//
160
161def NonNegIntAttrOp : TEST_Op<"non_negative_int_attr"> {
162  let arguments = (ins
163      Confined<I32Attr, [IntNonNegative]>:$i32attr,
164      Confined<I64Attr, [IntNonNegative]>:$i64attr
165  );
166}
167
168def PositiveIntAttrOp : TEST_Op<"positive_int_attr"> {
169  let arguments = (ins
170      Confined<I32Attr, [IntPositive]>:$i32attr,
171      Confined<I64Attr, [IntPositive]>:$i64attr
172  );
173}
174
175def TypeArrayAttrOp : TEST_Op<"type_array_attr"> {
176  let arguments = (ins TypeArrayAttr:$attr);
177}
178def TypeArrayAttrWithDefaultOp : TEST_Op<"type_array_attr_with_default"> {
179  let arguments = (ins DefaultValuedAttr<TypeArrayAttr, "{}">:$attr);
180}
181def TypeStringAttrWithTypeOp : TEST_Op<"string_attr_with_type"> {
182  let arguments = (ins TypedStrAttr<AnyType>:$attr);
183  let assemblyFormat = "$attr attr-dict";
184}
185
186def StrCaseA: StrEnumAttrCase<"A">;
187def StrCaseB: StrEnumAttrCase<"B">;
188
189def SomeStrEnum: StrEnumAttr<
190  "SomeStrEnum", "", [StrCaseA, StrCaseB]>;
191
192def StrEnumAttrOp : TEST_Op<"str_enum_attr"> {
193  let arguments = (ins SomeStrEnum:$attr);
194  let results = (outs I32:$val);
195}
196
197def I32Case5:  I32EnumAttrCase<"case5", 5>;
198def I32Case10: I32EnumAttrCase<"case10", 10>;
199
200def SomeI32Enum: I32EnumAttr<
201  "SomeI32Enum", "", [I32Case5, I32Case10]>;
202
203def I32EnumAttrOp : TEST_Op<"i32_enum_attr"> {
204  let arguments = (ins SomeI32Enum:$attr);
205  let results = (outs I32:$val);
206}
207
208def I64Case5:  I64EnumAttrCase<"case5", 5>;
209def I64Case10: I64EnumAttrCase<"case10", 10>;
210
211def SomeI64Enum: I64EnumAttr<
212  "SomeI64Enum", "", [I64Case5, I64Case10]>;
213
214def I64EnumAttrOp : TEST_Op<"i64_enum_attr"> {
215  let arguments = (ins SomeI64Enum:$attr);
216  let results = (outs I32:$val);
217}
218
219def SomeStructAttr : StructAttr<"SomeStructAttr", Test_Dialect, [
220  StructFieldAttr<"some_field", I64Attr>,
221  StructFieldAttr<"some_other_field", I64Attr>
222]> {}
223
224def StructAttrOp : TEST_Op<"struct_attr"> {
225  let arguments = (ins SomeStructAttr:$the_struct_attr);
226  let results = (outs);
227}
228
229def IntAttrOp : TEST_Op<"int_attrs"> {
230  let arguments = (ins
231    AnyI32Attr:$any_i32_attr,
232    IndexAttr:$index_attr,
233    UI32Attr:$ui32_attr,
234    SI32Attr:$si32_attr
235  );
236}
237
238def FloatElementsAttrOp : TEST_Op<"float_elements_attr"> {
239  let arguments = (ins
240      RankedF32ElementsAttr<[2]>:$scalar_f32_attr,
241      RankedF64ElementsAttr<[4, 8]>:$tensor_f64_attr
242  );
243}
244
245// A pattern that updates dense<[3.0, 4.0]> to dense<[5.0, 6.0]>.
246// This tests both matching and generating float elements attributes.
247def UpdateFloatElementsAttr : Pat<
248  (FloatElementsAttrOp
249    ConstantAttr<RankedF32ElementsAttr<[2]>, "{3.0f, 4.0f}">:$f32attr,
250    $f64attr),
251  (FloatElementsAttrOp
252    ConstantAttr<RankedF32ElementsAttr<[2]>, "{5.0f, 6.0f}">:$f32attr,
253    $f64attr)>;
254
255def IntElementsAttrOp : TEST_Op<"int_elements_attr"> {
256  let arguments = (ins
257      AnyI32ElementsAttr:$any_i32_attr,
258      I32ElementsAttr:$i32_attr
259  );
260}
261
262def RankedIntElementsAttrOp : TEST_Op<"ranked_int_elements_attr"> {
263  let arguments = (ins
264      RankedI32ElementsAttr<[2]>:$vector_i32_attr,
265      RankedI64ElementsAttr<[4, 8]>:$matrix_i64_attr
266  );
267}
268
269def DerivedTypeAttrOp : TEST_Op<"derived_type_attr", []> {
270  let results = (outs AnyTensor:$output);
271  DerivedTypeAttr element_dtype =
272    DerivedTypeAttr<"return getElementTypeOrSelf(output().getType());">;
273  DerivedAttr size = DerivedAttr<"int",
274    "return output().getType().cast<ShapedType>().getSizeInBits();",
275    "$_builder.getI32IntegerAttr($_self)">;
276}
277
278def StringElementsAttrOp : TEST_Op<"string_elements_attr"> {
279  let arguments = (ins
280      StringElementsAttr:$scalar_string_attr
281  );
282}
283
284//===----------------------------------------------------------------------===//
285// Test Attribute Constraints
286//===----------------------------------------------------------------------===//
287
288def SymbolRefOp : TEST_Op<"symbol_ref_attr"> {
289  let arguments = (ins
290    Confined<FlatSymbolRefAttr, [ReferToOp<"FuncOp">]>:$symbol
291  );
292}
293
294//===----------------------------------------------------------------------===//
295// Test Regions
296//===----------------------------------------------------------------------===//
297
298def OneRegionOp : TEST_Op<"one_region_op", []> {
299  let regions = (region AnyRegion);
300}
301
302def TwoRegionOp : TEST_Op<"two_region_op", []> {
303  let regions = (region AnyRegion, AnyRegion);
304}
305
306def SizedRegionOp : TEST_Op<"sized_region_op", []> {
307  let regions = (region SizedRegion<2>:$my_region, SizedRegion<1>);
308}
309
310//===----------------------------------------------------------------------===//
311// Test Call Interfaces
312//===----------------------------------------------------------------------===//
313
314def ConversionCallOp : TEST_Op<"conversion_call_op",
315    [CallOpInterface]> {
316  let arguments = (ins Variadic<AnyType>:$inputs, SymbolRefAttr:$callee);
317  let results = (outs Variadic<AnyType>);
318
319  let extraClassDeclaration = [{
320    /// Get the argument operands to the called function.
321    operand_range getArgOperands() { return inputs(); }
322
323    /// Return the callee of this operation.
324    CallInterfaceCallable getCallableForCallee() {
325      return (*this)->getAttrOfType<SymbolRefAttr>("callee");
326    }
327  }];
328}
329
330def FunctionalRegionOp : TEST_Op<"functional_region_op",
331    [CallableOpInterface]> {
332  let regions = (region AnyRegion:$body);
333  let results = (outs FunctionType);
334
335  let extraClassDeclaration = [{
336    Region *getCallableRegion() { return &body(); }
337    ArrayRef<Type> getCallableResults() {
338      return getType().cast<FunctionType>().getResults();
339    }
340  }];
341}
342
343
344def FoldToCallOp : TEST_Op<"fold_to_call_op"> {
345  let arguments = (ins FlatSymbolRefAttr:$callee);
346  let hasCanonicalizer = 1;
347}
348
349//===----------------------------------------------------------------------===//
350// Test Traits
351//===----------------------------------------------------------------------===//
352
353def SameOperandElementTypeOp : TEST_Op<"same_operand_element_type",
354    [SameOperandsElementType]> {
355  let arguments = (ins AnyType, AnyType);
356  let results = (outs AnyType);
357}
358
359def SameOperandAndResultElementTypeOp :
360    TEST_Op<"same_operand_and_result_element_type",
361    [SameOperandsAndResultElementType]> {
362  let arguments = (ins Variadic<AnyType>);
363  let results = (outs Variadic<AnyType>);
364}
365
366def SameOperandShapeOp : TEST_Op<"same_operand_shape", [SameOperandsShape]> {
367  let arguments = (ins Variadic<AnyShaped>);
368}
369
370def SameOperandAndResultShapeOp : TEST_Op<"same_operand_and_result_shape",
371    [SameOperandsAndResultShape]> {
372  let arguments = (ins Variadic<AnyShaped>);
373  let results = (outs Variadic<AnyShaped>);
374}
375
376def SameOperandAndResultTypeOp : TEST_Op<"same_operand_and_result_type",
377    [SameOperandsAndResultType]> {
378  let arguments = (ins Variadic<AnyType>);
379  let results = (outs Variadic<AnyType>);
380}
381
382def ElementwiseMappableOp : TEST_Op<"elementwise_mappable",
383    ElementwiseMappable.traits> {
384  let arguments = (ins Variadic<AnyType>);
385  let results = (outs Variadic<AnyType>);
386}
387
388def ArgAndResHaveFixedElementTypesOp :
389    TEST_Op<"arg_and_res_have_fixed_element_types",
390      [PredOpTrait<"fixed type combination",
391         And<[ElementTypeIsPred<"x", I32>,
392              ElementTypeIsPred<"y", F32>]>>,
393      ElementTypeIs<"res", I16>]> {
394  let arguments = (ins
395    AnyShaped:$x, AnyShaped:$y);
396  let results = (outs AnyShaped:$res);
397}
398
399def OperandsHaveSameElementType : TEST_Op<"operands_have_same_element_type", [
400    AllElementTypesMatch<["x", "y"]>]> {
401  let arguments = (ins AnyType:$x, AnyType:$y);
402}
403
404def OperandZeroAndResultHaveSameElementType : TEST_Op<
405    "operand0_and_result_have_same_element_type",
406    [AllElementTypesMatch<["x", "res"]>]> {
407  let arguments = (ins AnyType:$x, AnyType:$y);
408  let results = (outs AnyType:$res);
409}
410
411def OperandsHaveSameType :
412    TEST_Op<"operands_have_same_type", [AllTypesMatch<["x", "y"]>]> {
413  let arguments = (ins AnyType:$x, AnyType:$y);
414}
415
416def OperandZeroAndResultHaveSameType :
417    TEST_Op<"operand0_and_result_have_same_type",
418            [AllTypesMatch<["x", "res"]>]> {
419  let arguments = (ins AnyType:$x, AnyType:$y);
420  let results = (outs AnyType:$res);
421}
422
423def OperandsHaveSameRank :
424    TEST_Op<"operands_have_same_rank", [AllRanksMatch<["x", "y"]>]> {
425  let arguments = (ins AnyShaped:$x, AnyShaped:$y);
426}
427
428def OperandZeroAndResultHaveSameRank :
429    TEST_Op<"operand0_and_result_have_same_rank",
430            [AllRanksMatch<["x", "res"]>]> {
431  let arguments = (ins AnyShaped:$x, AnyShaped:$y);
432  let results = (outs AnyShaped:$res);
433}
434
435def OperandZeroAndResultHaveSameShape :
436    TEST_Op<"operand0_and_result_have_same_shape",
437            [AllShapesMatch<["x", "res"]>]> {
438  let arguments = (ins AnyShaped:$x, AnyShaped:$y);
439  let results = (outs AnyShaped:$res);
440}
441
442def OperandZeroAndResultHaveSameElementCount :
443    TEST_Op<"operand0_and_result_have_same_element_count",
444            [AllElementCountsMatch<["x", "res"]>]> {
445  let arguments = (ins AnyShaped:$x, AnyShaped:$y);
446  let results = (outs AnyShaped:$res);
447}
448
449def FourEqualsFive :
450    TEST_Op<"four_equals_five", [AllMatch<["5", "4"], "4 equals 5">]>;
451
452def OperandRankEqualsResultSize :
453    TEST_Op<"operand_rank_equals_result_size",
454            [AllMatch<[Rank<"operand">.result, ElementCount<"result">.result],
455                      "operand rank equals result size">]> {
456  let arguments = (ins AnyShaped:$operand);
457  let results = (outs AnyShaped:$result);
458}
459
460def IfFirstOperandIsNoneThenSoIsSecond :
461    TEST_Op<"if_first_operand_is_none_then_so_is_second", [PredOpTrait<
462    "has either both none type operands or first is not none",
463     Or<[
464        And<[TypeIsPred<"x", NoneType>, TypeIsPred<"y", NoneType>]>,
465        Neg<TypeIsPred<"x", NoneType>>]>>]> {
466  let arguments = (ins AnyType:$x, AnyType:$y);
467}
468
469def BroadcastableOp : TEST_Op<"broadcastable", [ResultsBroadcastableShape]> {
470  let arguments = (ins Variadic<AnyTensor>);
471  let results = (outs AnyTensor);
472}
473
474// HasParent trait
475def ParentOp : TEST_Op<"parent"> {
476    let regions = (region AnyRegion);
477}
478def ChildOp : TEST_Op<"child", [HasParent<"ParentOp">]>;
479
480// ParentOneOf trait
481def ParentOp1 : TEST_Op<"parent1"> {
482  let regions = (region AnyRegion);
483}
484def ChildWithParentOneOf : TEST_Op<"child_with_parent_one_of",
485                                [ParentOneOf<["ParentOp", "ParentOp1"]>]>;
486
487def TerminatorOp : TEST_Op<"finish", [Terminator]>;
488def SingleBlockImplicitTerminatorOp : TEST_Op<"SingleBlockImplicitTerminator",
489    [SingleBlockImplicitTerminator<"TerminatorOp">]> {
490  let regions = (region SizedRegion<1>:$region);
491}
492
493def I32ElementsAttrOp : TEST_Op<"i32ElementsAttr"> {
494  let arguments = (ins I32ElementsAttr:$attr);
495}
496
497def IndexElementsAttrOp : TEST_Op<"indexElementsAttr"> {
498  let arguments = (ins IndexElementsAttr:$attr);
499}
500
501def OpWithInferTypeInterfaceOp : TEST_Op<"op_with_infer_type_if", [
502    DeclareOpInterfaceMethods<InferTypeOpInterface>]> {
503  let arguments = (ins AnyTensor, AnyTensor);
504  let results = (outs AnyTensor);
505}
506
507def OpWithShapedTypeInferTypeInterfaceOp : TEST_Op<"op_with_shaped_type_infer_type_if",
508      InferTensorTypeWithReify.traits> {
509  let arguments = (ins AnyTensor, AnyTensor);
510  let results = (outs AnyTensor);
511}
512
513def IsNotScalar : Constraint<CPred<"$0.getType().getRank() != 0">>;
514
515def UpdateAttr : Pat<(I32ElementsAttrOp $attr),
516                     (I32ElementsAttrOp ConstantAttr<I32ElementsAttr, "0">),
517                     [(IsNotScalar $attr)]>;
518
519def TestBranchOp : TEST_Op<"br",
520    [DeclareOpInterfaceMethods<BranchOpInterface>, Terminator]> {
521  let arguments = (ins Variadic<AnyType>:$targetOperands);
522  let successors = (successor AnySuccessor:$target);
523}
524
525def AttrSizedOperandOp : TEST_Op<"attr_sized_operands",
526                                 [AttrSizedOperandSegments]> {
527  let arguments = (ins
528    Variadic<I32>:$a,
529    Variadic<I32>:$b,
530    I32:$c,
531    Variadic<I32>:$d,
532    I32ElementsAttr:$operand_segment_sizes
533  );
534}
535
536def AttrSizedResultOp : TEST_Op<"attr_sized_results",
537                                [AttrSizedResultSegments]> {
538  let arguments = (ins
539    I32ElementsAttr:$result_segment_sizes
540  );
541  let results = (outs
542    Variadic<I32>:$a,
543    Variadic<I32>:$b,
544    I32:$c,
545    Variadic<I32>:$d
546  );
547}
548
549// This is used to test encoding of a string attribute into an SSA name of a
550// pretty printed value name.
551def StringAttrPrettyNameOp
552 : TEST_Op<"string_attr_pretty_name",
553           [DeclareOpInterfaceMethods<OpAsmOpInterface>]> {
554  let arguments = (ins StrArrayAttr:$names);
555  let results = (outs Variadic<I32>:$r);
556
557  let printer = [{ return ::print(p, *this); }];
558  let parser = [{ return ::parse$cppClass(parser, result); }];
559}
560
561//===----------------------------------------------------------------------===//
562// Test Locations
563//===----------------------------------------------------------------------===//
564
565def TestLocationSrcOp : TEST_Op<"loc_src"> {
566  let arguments = (ins I32:$input);
567  let results = (outs I32:$output);
568}
569
570def TestLocationDstOp : TEST_Op<"loc_dst", [SameOperandsAndResultType]> {
571  let arguments = (ins I32:$input);
572  let results = (outs I32:$output);
573}
574
575//===----------------------------------------------------------------------===//
576// Test Patterns
577//===----------------------------------------------------------------------===//
578
579def OpA : TEST_Op<"op_a"> {
580  let arguments = (ins I32, I32Attr:$attr);
581  let results = (outs I32);
582}
583
584def OpB : TEST_Op<"op_b"> {
585  let arguments = (ins I32, I32Attr:$attr);
586  let results = (outs I32);
587}
588
589// Test named pattern.
590def TestNamedPatternRule : Pat<(OpA $input, $attr), (OpB $input, $attr)>;
591
592// Test with fused location.
593def : Pat<(OpA (OpA $input, $attr), $bttr), (OpB $input, $bttr)>;
594
595// Test added benefit.
596def OpD : TEST_Op<"op_d">, Arguments<(ins I32)>, Results<(outs I32)>;
597def OpE : TEST_Op<"op_e">, Arguments<(ins I32)>, Results<(outs I32)>;
598def OpF : TEST_Op<"op_f">, Arguments<(ins I32)>, Results<(outs I32)>;
599def OpG : TEST_Op<"op_g">, Arguments<(ins I32)>, Results<(outs I32)>;
600// Verify that bumping benefit results in selecting different op.
601def : Pat<(OpD $input), (OpE $input)>;
602def : Pat<(OpD $input), (OpF $input), [], (addBenefit 10)>;
603// Verify that patterns with more source nodes are selected before those with fewer.
604def : Pat<(OpG $input), (OpB $input, ConstantAttr<I32Attr, "20">:$attr)>;
605def : Pat<(OpG (OpG $input)), (OpB $input, ConstantAttr<I32Attr, "34">:$attr)>;
606
607// Test patterns for zero-result op.
608def OpH : TEST_Op<"op_h">, Arguments<(ins I32)>, Results<(outs)>;
609def OpI : TEST_Op<"op_i">, Arguments<(ins I32)>, Results<(outs)>;
610def : Pat<(OpH $input), (OpI $input)>;
611
612// Test patterns for zero-input op.
613def OpJ : TEST_Op<"op_j">, Arguments<(ins)>, Results<(outs I32)>;
614def OpK : TEST_Op<"op_k">, Arguments<(ins)>, Results<(outs I32)>;
615def : Pat<(OpJ), (OpK)>;
616
617// Test that natives calls are only called once during rewrites.
618def OpM : TEST_Op<"op_m"> {
619  let arguments = (ins I32, OptionalAttr<I32Attr>:$optional_attr);
620  let results = (outs I32);
621}
622
623def OpN : TEST_Op<"op_n"> {
624  let arguments = (ins I32, I32);
625  let results = (outs I32);
626}
627
628def OpO : TEST_Op<"op_o"> {
629  let arguments = (ins I32);
630  let results = (outs I32);
631}
632
633def OpP : TEST_Op<"op_p"> {
634  let arguments = (ins I32, I32, I32, I32, I32, I32);
635  let results = (outs I32);
636}
637
638// Test same operand name enforces equality condition check.
639def TestEqualArgsPattern : Pat<(OpN $a, $a), (OpO $a)>;
640
641// Test when equality is enforced at different depth.
642def TestNestedOpEqualArgsPattern :
643  Pat<(OpN $b, (OpP $a, $b, $c, $d, $e, $f)), (replaceWithValue $b)>;
644
645// Test multiple equal arguments check enforced.
646def TestMultipleEqualArgsPattern :
647  Pat<(OpP $a, $b, $a, $a, $b, $c), (OpN $c, $b)>;
648
649// Test for memrefs normalization of an op with normalizable memrefs.
650def OpNorm : TEST_Op<"op_norm", [MemRefsNormalizable]> {
651  let arguments = (ins AnyMemRef:$X, AnyMemRef:$Y);
652}
653// Test for memrefs normalization of an op without normalizable memrefs.
654def OpNonNorm : TEST_Op<"op_nonnorm"> {
655  let arguments = (ins AnyMemRef:$X, AnyMemRef:$Y);
656}
657// Test for memrefs normalization of an op that has normalizable memref results.
658def OpNormRet : TEST_Op<"op_norm_ret", [MemRefsNormalizable]> {
659  let arguments = (ins AnyMemRef:$X);
660  let results = (outs AnyMemRef:$Y, AnyMemRef:$Z);
661}
662
663// Test for memrefs normalization of an op with a reference to a function
664// symbol.
665def OpFuncRef : TEST_Op<"op_funcref"> {
666  let summary = "Test op with a reference to a function symbol";
667  let description = [{
668    The "test.op_funcref" is a test op with a reference to a function symbol.
669  }];
670  let builders = [OpBuilderDAG<(ins "FuncOp":$function)>];
671}
672
673// Pattern add the argument plus a increasing static number hidden in
674// OpMTest function. That value is set into the optional argument.
675// That way, we will know if operations is called once or twice.
676def OpMGetNullAttr : NativeCodeCall<"Attribute()">;
677def OpMAttributeIsNull : Constraint<CPred<"! ($_self)">, "Attribute is null">;
678def OpMVal : NativeCodeCall<"OpMTest($_builder, $0)">;
679def : Pat<(OpM $attr, $optAttr), (OpM $attr, (OpMVal $attr) ),
680    [(OpMAttributeIsNull:$optAttr)]>;
681
682// Test `$_` for ignoring op argument match.
683def TestIgnoreArgMatchSrcOp : TEST_Op<"ignore_arg_match_src"> {
684  let arguments = (ins
685    AnyType:$a, AnyType:$b, AnyType:$c,
686    AnyAttr:$d, AnyAttr:$e, AnyAttr:$f);
687}
688def TestIgnoreArgMatchDstOp : TEST_Op<"ignore_arg_match_dst"> {
689  let arguments = (ins AnyType:$b, AnyAttr:$f);
690}
691def : Pat<(TestIgnoreArgMatchSrcOp $_, $b, I32, I64Attr:$_, $_, $f),
692          (TestIgnoreArgMatchDstOp $b, $f)>;
693
694def OpInterleavedOperandAttribute1 : TEST_Op<"interleaved_operand_attr1"> {
695  let arguments = (ins
696    I32:$input1,
697    I64Attr:$attr1,
698    I32:$input2,
699    I64Attr:$attr2
700  );
701}
702
703def OpInterleavedOperandAttribute2 : TEST_Op<"interleaved_operand_attr2"> {
704  let arguments = (ins
705    I32:$input1,
706    I64Attr:$attr1,
707    I32:$input2,
708    I64Attr:$attr2
709  );
710}
711
712def ManyArgsOp : TEST_Op<"many_arguments"> {
713  let arguments = (ins
714    I32:$input1, I32:$input2, I32:$input3, I32:$input4, I32:$input5,
715    I32:$input6, I32:$input7, I32:$input8, I32:$input9,
716    I64Attr:$attr1, I64Attr:$attr2, I64Attr:$attr3, I64Attr:$attr4,
717    I64Attr:$attr5, I64Attr:$attr6, I64Attr:$attr7, I64Attr:$attr8,
718    I64Attr:$attr9
719  );
720}
721
722// Test that DRR does not blow up when seeing lots of arguments.
723def : Pat<(ManyArgsOp
724            $input1, $input2, $input3, $input4, $input5,
725            $input6, $input7, $input8, $input9,
726            ConstantAttr<I64Attr, "42">,
727            $attr2, $attr3, $attr4, $attr5, $attr6,
728            $attr7, $attr8, $attr9),
729          (ManyArgsOp
730            $input1, $input2, $input3, $input4, $input5,
731            $input6, $input7, $input8, $input9,
732            ConstantAttr<I64Attr, "24">,
733            $attr2, $attr3, $attr4, $attr5, $attr6,
734            $attr7, $attr8, $attr9)>;
735
736// Test that we can capture and reference interleaved operands and attributes.
737def : Pat<(OpInterleavedOperandAttribute1 $input1, $attr1, $input2, $attr2),
738          (OpInterleavedOperandAttribute2 $input1, $attr1, $input2, $attr2)>;
739
740// Test NativeCodeCall.
741def OpNativeCodeCall1 : TEST_Op<"native_code_call1"> {
742  let arguments = (ins
743    I32:$input1, I32:$input2,
744    BoolAttr:$choice,
745    I64Attr:$attr1, I64Attr:$attr2
746  );
747  let results = (outs I32);
748}
749def OpNativeCodeCall2 : TEST_Op<"native_code_call2"> {
750  let arguments = (ins I32:$input, I64ArrayAttr:$attr);
751  let results = (outs I32);
752}
753// Native code call to invoke a C++ function
754def CreateOperand: NativeCodeCall<"chooseOperand($0, $1, $2)">;
755// Native code call to invoke a C++ expression
756def CreateArrayAttr: NativeCodeCall<"$_builder.getArrayAttr({$0, $1})">;
757// Test that we can use NativeCodeCall to create operand and attribute.
758// This pattern chooses between $input1 and $input2 according to $choice and
759// it combines $attr1 and $attr2 into an array attribute.
760def : Pat<(OpNativeCodeCall1 $input1, $input2,
761                             ConstBoolAttrTrue:$choice, $attr1, $attr2),
762          (OpNativeCodeCall2 (CreateOperand $input1, $input2, $choice),
763                             (CreateArrayAttr $attr1, $attr2))>;
764// Note: the following is just for testing purpose.
765// Should use the replaceWithValue directive instead.
766def UseOpResult: NativeCodeCall<"$0">;
767// Test that we can use NativeCodeCall to create result.
768def : Pat<(OpNativeCodeCall1 $input1, $input2,
769                             ConstBoolAttrFalse, $attr1, $attr2),
770          (UseOpResult $input2)>;
771
772def OpNativeCodeCall3 : TEST_Op<"native_code_call3"> {
773  let arguments = (ins I32:$input);
774  let results = (outs I32);
775}
776// Test that NativeCodeCall is not ignored if it is not used to directly
777// replace the matched root op.
778def : Pattern<(OpNativeCodeCall3 $input),
779              [(NativeCodeCall<"createOpI($_builder, $_loc, $0)"> $input),
780               (OpK)]>;
781
782// Test AllAttrConstraintsOf.
783def OpAllAttrConstraint1 : TEST_Op<"all_attr_constraint_of1"> {
784  let arguments = (ins I64ArrayAttr:$attr);
785  let results = (outs I32);
786}
787def OpAllAttrConstraint2 : TEST_Op<"all_attr_constraint_of2"> {
788  let arguments = (ins I64ArrayAttr:$attr);
789  let results = (outs I32);
790}
791def Constraint0 : AttrConstraint<
792    CPred<"$_self.cast<ArrayAttr>()[0]."
793          "cast<IntegerAttr>().getInt() == 0">,
794    "[0] == 0">;
795def Constraint1 : AttrConstraint<
796    CPred<"$_self.cast<ArrayAttr>()[1].cast<IntegerAttr>().getInt() == 1">,
797    "[1] == 1">;
798def : Pat<(OpAllAttrConstraint1
799            AllAttrConstraintsOf<[Constraint0, Constraint1]>:$attr),
800          (OpAllAttrConstraint2 $attr)>;
801
802// Op for testing RewritePattern removing op with inner ops.
803def TestOpWithRegionPattern : TEST_Op<"op_with_region_pattern"> {
804  let regions = (region SizedRegion<1>:$region);
805  let hasCanonicalizer = 1;
806}
807
808def TestOpConstant : TEST_Op<"constant", [ConstantLike, NoSideEffect]> {
809  let arguments = (ins AnyAttr:$value);
810  let results = (outs AnyType);
811  let extraClassDeclaration = [{
812    Attribute getValue() { return (*this)->getAttr("value"); }
813  }];
814
815  let hasFolder = 1;
816}
817
818def OpR : TEST_Op<"op_r">, Arguments<(ins AnyInteger, AnyInteger)>, Results<(outs AnyInteger)>;
819def OpS : TEST_Op<"op_s">, Arguments<(ins AnyInteger, AnyAttr:$value)>, Results<(outs AnyInteger)>;
820
821def : Pat<(OpR $input1, (ConstantLikeMatcher I32Attr:$input2)),
822          (OpS:$unused $input1, $input2)>;
823
824// Op for testing trivial removal via folding of op with inner ops and no uses.
825def TestOpWithRegionFoldNoSideEffect : TEST_Op<
826    "op_with_region_fold_no_side_effect", [NoSideEffect]> {
827  let regions = (region SizedRegion<1>:$region);
828}
829
830// Op for testing folding of outer op with inner ops.
831def TestOpWithRegionFold : TEST_Op<"op_with_region_fold"> {
832  let arguments = (ins I32:$operand);
833  let results = (outs I32);
834  let regions = (region SizedRegion<1>:$region);
835  let hasFolder = 1;
836}
837
838def TestOpWithVariadicResultsAndFolder: TEST_Op<"op_with_variadic_results_and_folder"> {
839  let arguments = (ins Variadic<I32>:$operands);
840  let results = (outs Variadic<I32>);
841  let hasFolder = 1;
842}
843
844def TestCommutativeOp : TEST_Op<"op_commutative", [Commutative]> {
845  let arguments = (ins I32:$op1, I32:$op2, I32:$op3, I32:$op4);
846  let results = (outs I32);
847}
848
849def TestIdempotentTraitOp
850 : TEST_Op<"op_idempotent_trait",
851           [SameOperandsAndResultType, NoSideEffect, Idempotent]> {
852  let arguments = (ins I32:$op1);
853  let results = (outs I32);
854}
855
856def TestInvolutionTraitNoOperationFolderOp
857 : TEST_Op<"op_involution_trait_no_operation_fold",
858           [SameOperandsAndResultType, NoSideEffect, Involution]> {
859  let arguments = (ins I32:$op1);
860  let results = (outs I32);
861}
862
863def TestInvolutionTraitFailingOperationFolderOp
864 : TEST_Op<"op_involution_trait_failing_operation_fold",
865           [SameOperandsAndResultType, NoSideEffect, Involution]> {
866  let arguments = (ins I32:$op1);
867  let results = (outs I32);
868  let hasFolder = 1;
869}
870
871def TestInvolutionTraitSuccesfulOperationFolderOp
872 : TEST_Op<"op_involution_trait_succesful_operation_fold",
873           [SameOperandsAndResultType, NoSideEffect, Involution]> {
874  let arguments = (ins I32:$op1);
875  let results = (outs I32);
876  let hasFolder = 1;
877}
878
879def TestOpInPlaceFoldAnchor : TEST_Op<"op_in_place_fold_anchor"> {
880  let arguments = (ins I32);
881  let results = (outs I32);
882}
883
884def TestOpInPlaceFold : TEST_Op<"op_in_place_fold"> {
885  let arguments = (ins I32:$op, I32Attr:$attr);
886  let results = (outs I32);
887  let hasFolder = 1;
888}
889
890// An op that always fold itself.
891def TestPassthroughFold : TEST_Op<"passthrough_fold"> {
892  let arguments = (ins AnyType:$op);
893  let results = (outs AnyType);
894  let hasFolder = 1;
895}
896
897//===----------------------------------------------------------------------===//
898// Test Patterns (Symbol Binding)
899
900// Test symbol binding.
901def OpSymbolBindingA : TEST_Op<"symbol_binding_a", []> {
902  let arguments = (ins I32:$operand, I64Attr:$attr);
903  let results = (outs I32);
904}
905def OpSymbolBindingB : TEST_Op<"symbol_binding_b", []> {
906  let arguments = (ins I32:$operand);
907  let results = (outs I32);
908}
909def OpSymbolBindingC : TEST_Op<"symbol_binding_c", []> {
910  let arguments = (ins I32:$operand);
911  let results = (outs I32);
912  let builders = OpSymbolBindingB.builders;
913}
914def OpSymbolBindingD : TEST_Op<"symbol_binding_d", []> {
915  let arguments = (ins I32:$input1, I32:$input2, I64Attr:$attr);
916  let results = (outs I32);
917}
918def HasOneUse: Constraint<CPred<"$0.hasOneUse()">, "has one use">;
919def : Pattern<
920    // Bind to source pattern op operand/attribute/result
921    (OpSymbolBindingA:$res_a $operand, $attr), [
922        // Bind to auxiliary op result
923        (OpSymbolBindingC:$res_c (OpSymbolBindingB:$res_b $operand)),
924
925        // Use bound symbols in resultant ops
926        (OpSymbolBindingD $res_b, $res_c, $attr)],
927    // Use bound symbols in additional constraints
928    [(HasOneUse $res_a)]>;
929
930def OpSymbolBindingNoResult : TEST_Op<"symbol_binding_no_result", []> {
931  let arguments = (ins I32:$operand);
932}
933
934// Test that we can bind to an op without results and reference it later.
935def : Pat<(OpSymbolBindingNoResult:$op $operand),
936          (NativeCodeCall<"handleNoResultOp($_builder, $0)"> $op)>;
937
938//===----------------------------------------------------------------------===//
939// Test Patterns (Attributes)
940
941// Test matching against op attributes.
942def OpAttrMatch1 : TEST_Op<"match_op_attribute1"> {
943  let arguments = (ins
944    I32Attr:$required_attr,
945    OptionalAttr<I32Attr>:$optional_attr,
946    DefaultValuedAttr<I32Attr, "42">:$default_valued_attr,
947    I32Attr:$more_attr
948  );
949  let results = (outs I32);
950}
951def OpAttrMatch2 : TEST_Op<"match_op_attribute2"> {
952  let arguments = OpAttrMatch1.arguments;
953  let results = (outs I32);
954}
955def MoreConstraint : AttrConstraint<
956    CPred<"$_self.cast<IntegerAttr>().getInt() == 4">, "more constraint">;
957def : Pat<(OpAttrMatch1 $required, $optional, $default_valued,
958                        MoreConstraint:$more),
959          (OpAttrMatch2 $required, $optional, $default_valued, $more)>;
960
961// Test unit attrs.
962def OpAttrMatch3 : TEST_Op<"match_op_attribute3"> {
963  let arguments = (ins UnitAttr:$attr);
964  let results = (outs I32);
965}
966def OpAttrMatch4 : TEST_Op<"match_op_attribute4"> {
967  let arguments = (ins UnitAttr:$attr1, UnitAttr:$attr2);
968  let results = (outs I32);
969}
970def : Pat<(OpAttrMatch3 $attr), (OpAttrMatch4 ConstUnitAttr, $attr)>;
971
972// Test with constant attr.
973def OpC : TEST_Op<"op_c">, Arguments<(ins I32)>, Results<(outs I32)>;
974def : Pat<(OpC $input), (OpB $input, ConstantAttr<I32Attr, "17">:$attr)>;
975
976// Test string enum attribute in rewrites.
977def : Pat<(StrEnumAttrOp StrCaseA), (StrEnumAttrOp StrCaseB)>;
978// Test integer enum attribute in rewrites.
979def : Pat<(I32EnumAttrOp I32Case5), (I32EnumAttrOp I32Case10)>;
980def : Pat<(I64EnumAttrOp I64Case5), (I64EnumAttrOp I64Case10)>;
981
982//===----------------------------------------------------------------------===//
983// Test Patterns (Multi-result Ops)
984
985def MultiResultOpKind1: I64EnumAttrCase<"kind1", 1>;
986def MultiResultOpKind2: I64EnumAttrCase<"kind2", 2>;
987def MultiResultOpKind3: I64EnumAttrCase<"kind3", 3>;
988def MultiResultOpKind4: I64EnumAttrCase<"kind4", 4>;
989def MultiResultOpKind5: I64EnumAttrCase<"kind5", 5>;
990def MultiResultOpKind6: I64EnumAttrCase<"kind6", 6>;
991
992def MultiResultOpEnum: I64EnumAttr<
993  "MultiResultOpEnum", "Multi-result op kinds", [
994    MultiResultOpKind1, MultiResultOpKind2, MultiResultOpKind3,
995    MultiResultOpKind4, MultiResultOpKind5, MultiResultOpKind6
996  ]>;
997
998def ThreeResultOp : TEST_Op<"three_result"> {
999  let arguments = (ins MultiResultOpEnum:$kind);
1000  let results = (outs I32:$result1, F32:$result2, F32:$result3);
1001}
1002
1003def AnotherThreeResultOp : TEST_Op<"another_three_result", [DeclareOpInterfaceMethods<InferTypeOpInterface>]> {
1004  let arguments = (ins MultiResultOpEnum:$kind);
1005  let results = (outs I32:$result1, F32:$result2, F32:$result3);
1006}
1007
1008def TwoResultOp : TEST_Op<"two_result"> {
1009  let arguments = (ins MultiResultOpEnum:$kind);
1010  let results = (outs I32:$result1, F32:$result2);
1011}
1012
1013def AnotherTwoResultOp : TEST_Op<"another_two_result"> {
1014  let arguments = (ins MultiResultOpEnum:$kind);
1015  let results = (outs F32:$result1, F32:$result2);
1016}
1017
1018def OneResultOp1 : TEST_Op<"one_result1"> {
1019  let arguments = (ins MultiResultOpEnum:$kind);
1020  let results = (outs F32:$result1);
1021}
1022
1023def OneResultOp2 : TEST_Op<"one_result2"> {
1024  let arguments = (ins MultiResultOpEnum:$kind);
1025  let results = (outs I32:$result1);
1026}
1027
1028def OneResultOp3 : TEST_Op<"one_result3"> {
1029  let arguments = (ins F32);
1030  let results = (outs I32:$result1);
1031}
1032
1033// Test using multi-result op as a whole
1034def : Pat<(ThreeResultOp MultiResultOpKind1),
1035          (AnotherThreeResultOp MultiResultOpKind1)>;
1036
1037// Test using multi-result op as a whole for partial replacement
1038def : Pattern<(ThreeResultOp MultiResultOpKind2),
1039              [(TwoResultOp MultiResultOpKind2),
1040               (OneResultOp1 MultiResultOpKind2)]>;
1041def : Pattern<(ThreeResultOp MultiResultOpKind3),
1042              [(OneResultOp2 MultiResultOpKind3),
1043               (AnotherTwoResultOp MultiResultOpKind3)]>;
1044
1045// Test using results separately in a multi-result op
1046def : Pattern<(ThreeResultOp MultiResultOpKind4),
1047              [(TwoResultOp:$res1__0 MultiResultOpKind4),
1048               (OneResultOp1 MultiResultOpKind4),
1049               (TwoResultOp:$res2__1 MultiResultOpKind4)]>;
1050
1051// Test referencing a single value in the value pack
1052// This rule only matches TwoResultOp if its second result has no use.
1053def : Pattern<(TwoResultOp:$res MultiResultOpKind5),
1054              [(OneResultOp2 MultiResultOpKind5),
1055               (OneResultOp1 MultiResultOpKind5)],
1056              [(HasNoUseOf:$res__1)]>;
1057
1058// Test using auxiliary ops for replacing multi-result op
1059def : Pattern<
1060    (ThreeResultOp MultiResultOpKind6), [
1061        // Auxiliary op generated to help building the final result but not
1062        // directly used to replace the source op's results.
1063        (TwoResultOp:$interm MultiResultOpKind6),
1064
1065        (OneResultOp3 $interm__1),
1066        (AnotherTwoResultOp MultiResultOpKind6)
1067    ]>;
1068
1069//===----------------------------------------------------------------------===//
1070// Test Patterns (Variadic Ops)
1071
1072def OneVResOneVOperandOp1 : TEST_Op<"one_variadic_out_one_variadic_in1"> {
1073  let arguments = (ins Variadic<I32>);
1074  let results = (outs Variadic<I32>);
1075}
1076def OneVResOneVOperandOp2 : TEST_Op<"one_variadic_out_one_variadic_in2"> {
1077  let arguments = (ins Variadic<I32>);
1078  let results = (outs Variadic<I32>);
1079}
1080
1081// Rewrite an op with one variadic operand and one variadic result to
1082// another similar op.
1083def : Pat<(OneVResOneVOperandOp1 $inputs), (OneVResOneVOperandOp2 $inputs)>;
1084
1085def MixedVOperandOp1 : TEST_Op<"mixed_variadic_in1",
1086                               [SameVariadicOperandSize]> {
1087  let arguments = (ins
1088    Variadic<I32>:$input1,
1089    F32:$input2,
1090    Variadic<I32>:$input3
1091  );
1092}
1093
1094def MixedVOperandOp2 : TEST_Op<"mixed_variadic_in2",
1095                               [SameVariadicOperandSize]> {
1096  let arguments = (ins
1097    Variadic<I32>:$input1,
1098    F32:$input2,
1099    Variadic<I32>:$input3
1100  );
1101}
1102
1103// Rewrite an op with both variadic operands and normal operands.
1104def : Pat<(MixedVOperandOp1 $input1, $input2, $input3),
1105          (MixedVOperandOp2 $input1, $input2, $input3)>;
1106
1107def MixedVResultOp1 : TEST_Op<"mixed_variadic_out1", [SameVariadicResultSize]> {
1108  let results = (outs
1109    Variadic<I32>:$output1,
1110    F32:$output2,
1111    Variadic<I32>:$output3
1112  );
1113}
1114
1115def MixedVResultOp2 : TEST_Op<"mixed_variadic_out2", [SameVariadicResultSize]> {
1116  let results = (outs
1117    Variadic<I32>:$output1,
1118    F32:$output2,
1119    Variadic<I32>:$output3
1120  );
1121}
1122
1123// Rewrite an op with both variadic results and normal results.
1124// Note that because we are generating the op with a top-level result pattern,
1125// we are able to deduce the correct result types for the generated op using
1126// the information from the matched root op.
1127def : Pat<(MixedVResultOp1), (MixedVResultOp2)>;
1128
1129def OneI32ResultOp : TEST_Op<"one_i32_out"> {
1130  let results = (outs I32);
1131}
1132
1133def MixedVOperandOp3 : TEST_Op<"mixed_variadic_in3",
1134                               [SameVariadicOperandSize]> {
1135  let arguments = (ins
1136    I32:$input1,
1137    Variadic<I32>:$input2,
1138    Variadic<I32>:$input3,
1139    I32Attr:$count
1140  );
1141
1142  let results = (outs I32);
1143}
1144
1145def MixedVResultOp3 : TEST_Op<"mixed_variadic_out3",
1146                               [SameVariadicResultSize]> {
1147  let arguments = (ins I32Attr:$count);
1148
1149  let results = (outs
1150    I32:$output1,
1151    Variadic<I32>:$output2,
1152    Variadic<I32>:$output3
1153  );
1154
1155  // We will use this op in a nested result pattern, where we cannot deduce the
1156  // result type. So need to provide a builder not requiring result types.
1157  let builders = [
1158    OpBuilderDAG<(ins "IntegerAttr":$count),
1159    [{
1160      auto i32Type = $_builder.getIntegerType(32);
1161      $_state.addTypes(i32Type); // $output1
1162      SmallVector<Type, 4> types(count.getInt(), i32Type);
1163      $_state.addTypes(types); // $output2
1164      $_state.addTypes(types); // $output3
1165      $_state.addAttribute("count", count);
1166    }]>
1167  ];
1168}
1169
1170// Generates an op with variadic results using nested pattern.
1171def : Pat<(OneI32ResultOp),
1172          (MixedVOperandOp3
1173              (MixedVResultOp3:$results__0 ConstantAttr<I32Attr, "2">),
1174              (replaceWithValue $results__1),
1175              (replaceWithValue $results__2),
1176              ConstantAttr<I32Attr, "2">)>;
1177
1178//===----------------------------------------------------------------------===//
1179// Test Patterns (Location)
1180
1181// Test that we can specify locations for generated ops.
1182def : Pat<(TestLocationSrcOp:$res1
1183           (TestLocationSrcOp:$res2
1184            (TestLocationSrcOp:$res3 $input))),
1185          (TestLocationDstOp
1186            (TestLocationDstOp
1187              (TestLocationDstOp $input, (location $res1)),
1188              (location "named")),
1189            (location "fused", $res2, $res3))>;
1190
1191//===----------------------------------------------------------------------===//
1192// Test Legalization
1193//===----------------------------------------------------------------------===//
1194
1195def Test_LegalizerEnum_Success : StrEnumAttrCase<"Success">;
1196def Test_LegalizerEnum_Failure : StrEnumAttrCase<"Failure">;
1197
1198def Test_LegalizerEnum : StrEnumAttr<"Success", "Failure",
1199  [Test_LegalizerEnum_Success, Test_LegalizerEnum_Failure]>;
1200
1201def ILLegalOpA : TEST_Op<"illegal_op_a">, Results<(outs I32)>;
1202def ILLegalOpB : TEST_Op<"illegal_op_b">, Results<(outs I32)>;
1203def ILLegalOpC : TEST_Op<"illegal_op_c">, Results<(outs I32)>;
1204def ILLegalOpD : TEST_Op<"illegal_op_d">, Results<(outs I32)>;
1205def ILLegalOpE : TEST_Op<"illegal_op_e">, Results<(outs I32)>;
1206def ILLegalOpF : TEST_Op<"illegal_op_f">, Results<(outs I32)>;
1207def LegalOpA : TEST_Op<"legal_op_a">,
1208  Arguments<(ins Test_LegalizerEnum:$status)>, Results<(outs I32)>;
1209def LegalOpB : TEST_Op<"legal_op_b">, Results<(outs I32)>;
1210
1211// Check that the conversion infrastructure can properly undo the creation of
1212// operations where an operation was created before its parent, in this case,
1213// in the parent's builder.
1214def IllegalOpTerminator : TEST_Op<"illegal_op_terminator", [Terminator]>;
1215def IllegalOpWithRegion : TEST_Op<"illegal_op_with_region"> {
1216  let skipDefaultBuilders = 1;
1217  let builders = [OpBuilderDAG<(ins),
1218    [{
1219       Region *bodyRegion = $_state.addRegion();
1220       OpBuilder::InsertionGuard g($_builder);
1221       Block *body = $_builder.createBlock(bodyRegion);
1222       $_builder.setInsertionPointToEnd(body);
1223       $_builder.create<IllegalOpTerminator>($_state.location);
1224    }]>];
1225}
1226def IllegalOpWithRegionAnchor : TEST_Op<"illegal_op_with_region_anchor">;
1227
1228// Check that smaller pattern depths are chosen, i.e. prioritize more direct
1229// mappings.
1230def : Pat<(ILLegalOpA), (LegalOpA Test_LegalizerEnum_Success)>;
1231
1232def : Pat<(ILLegalOpA), (ILLegalOpB)>;
1233def : Pat<(ILLegalOpB), (LegalOpA Test_LegalizerEnum_Failure)>;
1234
1235// Check that the higher benefit pattern is taken for multiple legalizations
1236// with the same depth.
1237def : Pat<(ILLegalOpC), (ILLegalOpD)>;
1238def : Pat<(ILLegalOpD), (LegalOpA Test_LegalizerEnum_Failure)>;
1239
1240def : Pat<(ILLegalOpC), (ILLegalOpE), [], (addBenefit 10)>;
1241def : Pat<(ILLegalOpE), (LegalOpA Test_LegalizerEnum_Success)>;
1242
1243// Check that patterns use the most up-to-date value when being replaced.
1244def TestRewriteOp : TEST_Op<"rewrite">,
1245  Arguments<(ins AnyType)>, Results<(outs AnyType)>;
1246def : Pat<(TestRewriteOp $input), (replaceWithValue $input)>;
1247
1248// Check that patterns can specify bounded recursion when rewriting.
1249def TestRecursiveRewriteOp : TEST_Op<"recursive_rewrite"> {
1250  let arguments = (ins I64Attr:$depth);
1251  let assemblyFormat = "$depth attr-dict";
1252}
1253
1254//===----------------------------------------------------------------------===//
1255// Test Type Legalization
1256//===----------------------------------------------------------------------===//
1257
1258def TestRegionBuilderOp : TEST_Op<"region_builder">;
1259def TestReturnOp : TEST_Op<"return", [ReturnLike, Terminator]> {
1260  let arguments = (ins Variadic<AnyType>);
1261  let builders = [OpBuilderDAG<(ins),
1262    [{ build($_builder, $_state, {}); }]>
1263  ];
1264}
1265def TestCastOp : TEST_Op<"cast">,
1266  Arguments<(ins Variadic<AnyType>)>, Results<(outs AnyType)>;
1267def TestInvalidOp : TEST_Op<"invalid", [Terminator]>,
1268  Arguments<(ins Variadic<AnyType>)>;
1269def TestTypeProducerOp : TEST_Op<"type_producer">,
1270  Results<(outs AnyType)>;
1271def TestAnotherTypeProducerOp : TEST_Op<"another_type_producer">,
1272  Results<(outs AnyType)>;
1273def TestTypeConsumerOp : TEST_Op<"type_consumer">,
1274  Arguments<(ins AnyType)>;
1275def TestValidOp : TEST_Op<"valid", [Terminator]>,
1276  Arguments<(ins Variadic<AnyType>)>;
1277
1278def TestMergeBlocksOp : TEST_Op<"merge_blocks"> {
1279  let summary = "merge_blocks operation";
1280  let description = [{
1281    Test op with multiple blocks that are merged with Dialect Conversion"
1282  }];
1283
1284  let regions = (region AnyRegion:$body);
1285  let results = (outs Variadic<AnyType>:$result);
1286}
1287
1288def TestSignatureConversionUndoOp : TEST_Op<"signature_conversion_undo"> {
1289  let regions = (region AnyRegion);
1290}
1291
1292//===----------------------------------------------------------------------===//
1293// Test parser.
1294//===----------------------------------------------------------------------===//
1295
1296def ParseIntegerLiteralOp : TEST_Op<"parse_integer_literal"> {
1297  let results = (outs Variadic<Index>:$results);
1298  let parser = [{ return ::parse$cppClass(parser, result); }];
1299  let printer = [{ return ::print(p, *this); }];
1300}
1301
1302def ParseWrappedKeywordOp : TEST_Op<"parse_wrapped_keyword"> {
1303  let arguments = (ins StrAttr:$keyword);
1304  let parser = [{ return ::parse$cppClass(parser, result); }];
1305  let printer = [{ return ::print(p, *this); }];
1306}
1307
1308//===----------------------------------------------------------------------===//
1309// Test region argument list parsing.
1310
1311def IsolatedRegionOp : TEST_Op<"isolated_region", [IsolatedFromAbove]> {
1312  let summary =  "isolated region operation";
1313  let description = [{
1314    Test op with an isolated region, to test passthrough region arguments. Each
1315    argument is of index type.
1316  }];
1317
1318  let arguments = (ins Index);
1319  let regions = (region SizedRegion<1>:$region);
1320  let parser = [{ return ::parse$cppClass(parser, result); }];
1321  let printer = [{ return ::print(p, *this); }];
1322}
1323
1324def SSACFGRegionOp : TEST_Op<"ssacfg_region",  [
1325    DeclareOpInterfaceMethods<RegionKindInterface>]> {
1326  let summary =  "operation with an SSACFG region";
1327  let description = [{
1328    Test op that defines an SSACFG region.
1329  }];
1330
1331  let regions = (region VariadicRegion<AnyRegion>:$regions);
1332  let arguments = (ins Variadic<AnyType>);
1333  let results = (outs Variadic<AnyType>);
1334}
1335
1336def GraphRegionOp : TEST_Op<"graph_region",  [
1337    DeclareOpInterfaceMethods<RegionKindInterface>]> {
1338  let summary =  "operation with a graph region";
1339  let description = [{
1340    Test op that defines a graph region.
1341  }];
1342
1343  let regions = (region AnyRegion:$region);
1344  let parser = [{ return ::parse$cppClass(parser, result); }];
1345  let printer = [{ return ::print(p, *this); }];
1346}
1347
1348def AffineScopeOp : TEST_Op<"affine_scope", [AffineScope]> {
1349  let summary =  "affine scope operation";
1350  let description = [{
1351    Test op that defines a new affine scope.
1352  }];
1353
1354  let regions = (region SizedRegion<1>:$region);
1355  let parser = [{ return ::parse$cppClass(parser, result); }];
1356  let printer = [{ return ::print(p, *this); }];
1357}
1358
1359def WrappingRegionOp : TEST_Op<"wrapping_region",
1360    [SingleBlockImplicitTerminator<"TestReturnOp">]> {
1361  let summary =  "wrapping region operation";
1362  let description = [{
1363    Test op wrapping another op in a region, to test calling
1364    parseGenericOperation from the custom parser.
1365  }];
1366
1367  let results = (outs Variadic<AnyType>);
1368  let regions = (region SizedRegion<1>:$region);
1369  let parser = [{ return ::parse$cppClass(parser, result); }];
1370  let printer = [{ return ::print(p, *this); }];
1371}
1372
1373def PolyForOp : TEST_Op<"polyfor">
1374{
1375  let summary =  "polyfor operation";
1376  let description = [{
1377    Test op with multiple region arguments, each argument of index type.
1378  }];
1379
1380  let regions = (region SizedRegion<1>:$region);
1381  let parser = [{ return ::parse$cppClass(parser, result); }];
1382}
1383
1384//===----------------------------------------------------------------------===//
1385// Test OpAsmInterface.
1386
1387def AsmInterfaceOp : TEST_Op<"asm_interface_op"> {
1388  let results = (outs AnyType:$first, Variadic<AnyType>:$middle_results,
1389                      AnyType);
1390}
1391
1392def AsmDialectInterfaceOp : TEST_Op<"asm_dialect_interface_op"> {
1393  let results = (outs AnyType);
1394}
1395
1396//===----------------------------------------------------------------------===//
1397// Test Op Asm Format
1398//===----------------------------------------------------------------------===//
1399
1400def FormatLiteralOp : TEST_Op<"format_literal_op"> {
1401  let assemblyFormat = [{
1402    `keyword_$.` `->` `:` `,` `=` `<` `>` `(` `)` `[` `]` `` `(` ` ` `)`
1403    `?` `+` `*` `{` `\n` `}` attr-dict
1404  }];
1405}
1406
1407// Test that we elide attributes that are within the syntax.
1408def FormatAttrOp : TEST_Op<"format_attr_op"> {
1409  let arguments = (ins I64Attr:$attr);
1410  let assemblyFormat = "$attr attr-dict";
1411}
1412
1413// Test that we elide optional attributes that are within the syntax.
1414def FormatOptAttrAOp : TEST_Op<"format_opt_attr_op_a"> {
1415  let arguments = (ins OptionalAttr<I64Attr>:$opt_attr);
1416  let assemblyFormat = "(`(` $opt_attr^ `)` )? attr-dict";
1417}
1418def FormatOptAttrBOp : TEST_Op<"format_opt_attr_op_b"> {
1419  let arguments = (ins OptionalAttr<I64Attr>:$opt_attr);
1420  let assemblyFormat = "($opt_attr^)? attr-dict";
1421}
1422
1423// Test that we format symbol name attributes properly.
1424def FormatSymbolNameAttrOp : TEST_Op<"format_symbol_name_attr_op"> {
1425  let arguments = (ins SymbolNameAttr:$attr);
1426  let assemblyFormat = "$attr attr-dict";
1427}
1428
1429// Test that we format optional symbol name attributes properly.
1430def FormatOptSymbolNameAttrOp : TEST_Op<"format_opt_symbol_name_attr_op"> {
1431  let arguments = (ins OptionalAttr<SymbolNameAttr>:$opt_attr);
1432  let assemblyFormat = "($opt_attr^)? attr-dict";
1433}
1434
1435// Test that we elide attributes that are within the syntax.
1436def FormatAttrDictWithKeywordOp : TEST_Op<"format_attr_dict_w_keyword"> {
1437  let arguments = (ins I64Attr:$attr, OptionalAttr<I64Attr>:$opt_attr);
1438  let assemblyFormat = "attr-dict-with-keyword";
1439}
1440
1441// Test that we don't need to provide types in the format if they are buildable.
1442def FormatBuildableTypeOp : TEST_Op<"format_buildable_type_op"> {
1443  let arguments = (ins I64:$buildable);
1444  let results = (outs I64:$buildable_res);
1445  let assemblyFormat = "$buildable attr-dict";
1446}
1447
1448// Test various mixings of region formatting.
1449class FormatRegionBase<string suffix, string fmt>
1450    : TEST_Op<"format_region_" # suffix # "_op"> {
1451  let regions = (region AnyRegion:$region);
1452  let assemblyFormat = fmt;
1453}
1454def FormatRegionAOp : FormatRegionBase<"a", [{
1455  regions attr-dict
1456}]>;
1457def FormatRegionBOp : FormatRegionBase<"b", [{
1458  $region attr-dict
1459}]>;
1460def FormatRegionCOp : FormatRegionBase<"c", [{
1461  (`region` $region^)? attr-dict
1462}]>;
1463class FormatVariadicRegionBase<string suffix, string fmt>
1464    : TEST_Op<"format_variadic_region_" # suffix # "_op"> {
1465  let regions = (region VariadicRegion<AnyRegion>:$regions);
1466  let assemblyFormat = fmt;
1467}
1468def FormatVariadicRegionAOp : FormatVariadicRegionBase<"a", [{
1469  $regions attr-dict
1470}]>;
1471def FormatVariadicRegionBOp : FormatVariadicRegionBase<"b", [{
1472  ($regions^ `found_regions`)? attr-dict
1473}]>;
1474class FormatRegionImplicitTerminatorBase<string suffix, string fmt>
1475    : TEST_Op<"format_implicit_terminator_region_" # suffix # "_op",
1476              [SingleBlockImplicitTerminator<"TestReturnOp">]> {
1477  let regions = (region AnyRegion:$region);
1478  let assemblyFormat = fmt;
1479}
1480def FormatFormatRegionImplicitTerminatorAOp
1481    : FormatRegionImplicitTerminatorBase<"a", [{
1482  $region attr-dict
1483}]>;
1484
1485// Test various mixings of result type formatting.
1486class FormatResultBase<string suffix, string fmt>
1487    : TEST_Op<"format_result_" # suffix # "_op"> {
1488  let results = (outs I64:$buildable_res, AnyMemRef:$result);
1489  let assemblyFormat = fmt;
1490}
1491def FormatResultAOp : FormatResultBase<"a", [{
1492  type($result) attr-dict
1493}]>;
1494def FormatResultBOp : FormatResultBase<"b", [{
1495  type(results) attr-dict
1496}]>;
1497def FormatResultCOp : FormatResultBase<"c", [{
1498  functional-type($buildable_res, $result) attr-dict
1499}]>;
1500
1501def FormatVariadicResult : TEST_Op<"format_variadic_result"> {
1502  let results = (outs Variadic<I64>:$result);
1503  let assemblyFormat = [{ `:` type($result) attr-dict}];
1504}
1505
1506def FormatMultipleVariadicResults : TEST_Op<"format_multiple_variadic_results",
1507                                            [AttrSizedResultSegments]> {
1508  let results = (outs Variadic<I64>:$result0, Variadic<AnyType>:$result1);
1509  let assemblyFormat = [{
1510    `:` `(` type($result0) `)` `,` `(` type($result1) `)` attr-dict
1511  }];
1512}
1513
1514// Test various mixings of operand type formatting.
1515class FormatOperandBase<string suffix, string fmt>
1516    : TEST_Op<"format_operand_" # suffix # "_op"> {
1517  let arguments = (ins I64:$buildable, AnyMemRef:$operand);
1518  let assemblyFormat = fmt;
1519}
1520
1521def FormatOperandAOp : FormatOperandBase<"a", [{
1522  operands `:` type(operands) attr-dict
1523}]>;
1524def FormatOperandBOp : FormatOperandBase<"b", [{
1525  operands `:` type($operand) attr-dict
1526}]>;
1527def FormatOperandCOp : FormatOperandBase<"c", [{
1528  $buildable `,` $operand `:` type(operands) attr-dict
1529}]>;
1530def FormatOperandDOp : FormatOperandBase<"d", [{
1531  $buildable `,` $operand `:` type($operand) attr-dict
1532}]>;
1533def FormatOperandEOp : FormatOperandBase<"e", [{
1534  $buildable `,` $operand `:` type($buildable) `,` type($operand) attr-dict
1535}]>;
1536
1537def FormatSuccessorAOp : TEST_Op<"format_successor_a_op", [Terminator]> {
1538  let successors = (successor VariadicSuccessor<AnySuccessor>:$targets);
1539  let assemblyFormat = "$targets attr-dict";
1540}
1541
1542def FormatVariadicOperand : TEST_Op<"format_variadic_operand"> {
1543  let arguments = (ins Variadic<I64>:$operand);
1544  let assemblyFormat = [{ $operand `:` type($operand) attr-dict}];
1545}
1546
1547def FormatMultipleVariadicOperands :
1548    TEST_Op<"format_multiple_variadic_operands", [AttrSizedOperandSegments]> {
1549  let arguments = (ins Variadic<I64>:$operand0, Variadic<AnyType>:$operand1);
1550  let assemblyFormat = [{
1551    ` ` `(` $operand0 `)` `,` `(` $operand1 `:` type($operand1) `)` attr-dict
1552  }];
1553}
1554
1555// Test various mixings of optional operand and result type formatting.
1556class FormatOptionalOperandResultOpBase<string suffix, string fmt>
1557    : TEST_Op<"format_optional_operand_result_" # suffix # "_op",
1558              [AttrSizedOperandSegments]> {
1559  let arguments = (ins Optional<I64>:$optional, Variadic<I64>:$variadic);
1560  let results = (outs Optional<I64>:$optional_res);
1561  let assemblyFormat = fmt;
1562}
1563
1564def FormatOptionalOperandResultAOp : FormatOptionalOperandResultOpBase<"a", [{
1565  `(` $optional `:` type($optional) `)` `:` type($optional_res)
1566  (`[` $variadic^ `]`)? attr-dict
1567}]>;
1568
1569def FormatOptionalOperandResultBOp : FormatOptionalOperandResultOpBase<"b", [{
1570  (`(` $optional^ `:` type($optional) `)`)? `:` type($optional_res)
1571  (`[` $variadic^ `]`)? attr-dict
1572}]>;
1573
1574// Test optional result type formatting.
1575class FormatOptionalResultOpBase<string suffix, string fmt>
1576    : TEST_Op<"format_optional_result_" # suffix # "_op",
1577              [AttrSizedResultSegments]> {
1578  let results = (outs Optional<I64>:$optional, Variadic<I64>:$variadic);
1579  let assemblyFormat = fmt;
1580}
1581def FormatOptionalResultAOp : FormatOptionalResultOpBase<"a", [{
1582  (`:` type($optional)^ `->` type($variadic))? attr-dict
1583}]>;
1584
1585def FormatOptionalResultBOp : FormatOptionalResultOpBase<"b", [{
1586  (`:` type($optional) `->` type($variadic)^)? attr-dict
1587}]>;
1588
1589def FormatOptionalResultCOp : FormatOptionalResultOpBase<"c", [{
1590  (`:` functional-type($optional, $variadic)^)? attr-dict
1591}]>;
1592
1593def FormatTwoVariadicOperandsNoBuildableTypeOp
1594    : TEST_Op<"format_two_variadic_operands_no_buildable_type_op",
1595              [AttrSizedOperandSegments]> {
1596  let arguments = (ins Variadic<AnyType>:$a,
1597                       Variadic<AnyType>:$b);
1598  let assemblyFormat = [{
1599    `(` $a `:` type($a) `)` `->` `(` $b `:` type($b) `)`  attr-dict
1600  }];
1601}
1602
1603def FormatInferVariadicTypeFromNonVariadic
1604    : TEST_Op<"format_infer_variadic_type_from_non_variadic",
1605              [SameOperandsAndResultType]> {
1606  let arguments = (ins Variadic<AnyType>:$operands);
1607  let results = (outs AnyType:$result);
1608  let assemblyFormat = "$operands attr-dict `:` type($result)";
1609}
1610
1611def FormatOptionalUnitAttr : TEST_Op<"format_optional_unit_attribute"> {
1612  let arguments = (ins UnitAttr:$is_optional);
1613  let assemblyFormat = "(`is_optional` $is_optional^)? attr-dict";
1614}
1615
1616def FormatOptionalUnitAttrNoElide
1617    : TEST_Op<"format_optional_unit_attribute_no_elide"> {
1618  let arguments = (ins UnitAttr:$is_optional);
1619  let assemblyFormat = "($is_optional^)? attr-dict";
1620}
1621
1622def FormatOptionalEnumAttr : TEST_Op<"format_optional_enum_attr"> {
1623  let arguments = (ins OptionalAttr<SomeI64Enum>:$attr);
1624  let assemblyFormat = "($attr^)? attr-dict";
1625}
1626
1627//===----------------------------------------------------------------------===//
1628// Custom Directives
1629
1630def FormatCustomDirectiveOperands
1631    : TEST_Op<"format_custom_directive_operands", [AttrSizedOperandSegments]> {
1632  let arguments = (ins I64:$operand, Optional<I64>:$optOperand,
1633                       Variadic<I64>:$varOperands);
1634  let assemblyFormat = [{
1635    custom<CustomDirectiveOperands>(
1636      $operand, $optOperand, $varOperands
1637    )
1638    attr-dict
1639  }];
1640}
1641
1642def FormatCustomDirectiveOperandsAndTypes
1643    : TEST_Op<"format_custom_directive_operands_and_types",
1644              [AttrSizedOperandSegments]> {
1645  let arguments = (ins AnyType:$operand, Optional<AnyType>:$optOperand,
1646                       Variadic<AnyType>:$varOperands);
1647  let assemblyFormat = [{
1648    custom<CustomDirectiveOperandsAndTypes>(
1649      $operand, $optOperand, $varOperands,
1650      type($operand), type($optOperand), type($varOperands)
1651    )
1652    attr-dict
1653  }];
1654}
1655
1656def FormatCustomDirectiveRegions : TEST_Op<"format_custom_directive_regions"> {
1657  let regions = (region AnyRegion:$region, VariadicRegion<AnyRegion>:$regions);
1658  let assemblyFormat = [{
1659    custom<CustomDirectiveRegions>(
1660      $region, $regions
1661    )
1662    attr-dict
1663  }];
1664}
1665
1666def FormatCustomDirectiveResults
1667    : TEST_Op<"format_custom_directive_results", [AttrSizedResultSegments]> {
1668  let results = (outs AnyType:$result, Optional<AnyType>:$optResult,
1669                      Variadic<AnyType>:$varResults);
1670  let assemblyFormat = [{
1671    custom<CustomDirectiveResults>(
1672      type($result), type($optResult), type($varResults)
1673    )
1674    attr-dict
1675  }];
1676}
1677
1678def FormatCustomDirectiveResultsWithTypeRefs
1679    : TEST_Op<"format_custom_directive_results_with_type_refs",
1680              [AttrSizedResultSegments]> {
1681  let results = (outs AnyType:$result, Optional<AnyType>:$optResult,
1682                      Variadic<AnyType>:$varResults);
1683  let assemblyFormat = [{
1684    custom<CustomDirectiveResults>(
1685      type($result), type($optResult), type($varResults)
1686    )
1687    custom<CustomDirectiveWithTypeRefs>(
1688      ref(type($result)), ref(type($optResult)), ref(type($varResults))
1689    )
1690    attr-dict
1691  }];
1692}
1693
1694def FormatCustomDirectiveWithOptionalOperandRef
1695    : TEST_Op<"format_custom_directive_with_optional_operand_ref"> {
1696  let arguments = (ins Optional<I64>:$optOperand);
1697  let assemblyFormat = [{
1698    ($optOperand^)? `:`
1699    custom<CustomDirectiveOptionalOperandRef>(ref($optOperand))
1700    attr-dict
1701  }];
1702}
1703
1704def FormatCustomDirectiveSuccessors
1705    : TEST_Op<"format_custom_directive_successors", [Terminator]> {
1706  let successors = (successor AnySuccessor:$successor,
1707                              VariadicSuccessor<AnySuccessor>:$successors);
1708  let assemblyFormat = [{
1709    custom<CustomDirectiveSuccessors>(
1710      $successor, $successors
1711    )
1712    attr-dict
1713  }];
1714}
1715
1716def FormatCustomDirectiveAttributes
1717    : TEST_Op<"format_custom_directive_attributes"> {
1718  let arguments = (ins I64Attr:$attr, OptionalAttr<I64Attr>:$optAttr);
1719  let assemblyFormat = [{
1720    custom<CustomDirectiveAttributes>(
1721      $attr, $optAttr
1722    )
1723    attr-dict
1724  }];
1725}
1726
1727def FormatCustomDirectiveAttrDict
1728    : TEST_Op<"format_custom_directive_attrdict"> {
1729  let arguments = (ins I64Attr:$attr, OptionalAttr<I64Attr>:$optAttr);
1730  let assemblyFormat = [{
1731    custom<CustomDirectiveAttrDict>( attr-dict )
1732  }];
1733}
1734
1735//===----------------------------------------------------------------------===//
1736// AllTypesMatch type inference
1737
1738def FormatAllTypesMatchVarOp : TEST_Op<"format_all_types_match_var", [
1739    AllTypesMatch<["value1", "value2", "result"]>
1740  ]> {
1741  let arguments = (ins AnyType:$value1, AnyType:$value2);
1742  let results = (outs AnyType:$result);
1743  let assemblyFormat = "attr-dict $value1 `,` $value2 `:` type($value1)";
1744}
1745
1746def FormatAllTypesMatchAttrOp : TEST_Op<"format_all_types_match_attr", [
1747    AllTypesMatch<["value1", "value2", "result"]>
1748  ]> {
1749  let arguments = (ins AnyAttr:$value1, AnyType:$value2);
1750  let results = (outs AnyType:$result);
1751  let assemblyFormat = "attr-dict $value1 `,` $value2";
1752}
1753
1754//===----------------------------------------------------------------------===//
1755// TypesMatchWith type inference
1756
1757def FormatTypesMatchVarOp : TEST_Op<"format_types_match_var", [
1758    TypesMatchWith<"result type matches operand", "value", "result", "$_self">
1759  ]> {
1760  let arguments = (ins AnyType:$value);
1761  let results = (outs AnyType:$result);
1762  let assemblyFormat = "attr-dict $value `:` type($value)";
1763}
1764
1765def FormatTypesMatchVariadicOp : TEST_Op<"format_types_match_variadic", [
1766    RangedTypesMatchWith<"result type matches operand", "value", "result",
1767                         "llvm::make_range($_self.begin(), $_self.end())">
1768  ]> {
1769  let arguments = (ins Variadic<AnyType>:$value);
1770  let results = (outs Variadic<AnyType>:$result);
1771  let assemblyFormat = "attr-dict $value `:` type($value)";
1772}
1773
1774def FormatTypesMatchAttrOp : TEST_Op<"format_types_match_attr", [
1775    TypesMatchWith<"result type matches constant", "value", "result", "$_self">
1776  ]> {
1777  let arguments = (ins AnyAttr:$value);
1778  let results = (outs AnyType:$result);
1779  let assemblyFormat = "attr-dict $value";
1780}
1781
1782//===----------------------------------------------------------------------===//
1783// Test SideEffects
1784//===----------------------------------------------------------------------===//
1785
1786def SideEffectOp : TEST_Op<"side_effect_op",
1787    [DeclareOpInterfaceMethods<MemoryEffectsOpInterface>,
1788     DeclareOpInterfaceMethods<TestEffectOpInterface>]> {
1789  let results = (outs AnyType:$result);
1790}
1791
1792//===----------------------------------------------------------------------===//
1793// Test CopyOpInterface
1794//===----------------------------------------------------------------------===//
1795
1796def CopyOp : TEST_Op<"copy", [CopyOpInterface]> {
1797  let description = [{
1798    Represents a copy operation.
1799  }];
1800  let arguments = (ins Res<AnyMemRef, "", [MemRead]>:$source,
1801                   Res<AnyMemRef, "", [MemWrite]>:$target);
1802  let assemblyFormat = [{
1803    `(` $source `,` $target `)` `:` `(` type($source) `,` type($target) `)`
1804     attr-dict
1805  }];
1806  let extraClassDeclaration = [{
1807    Value getSource() { return source(); }
1808    Value getTarget() { return target(); }
1809  }];
1810}
1811
1812//===----------------------------------------------------------------------===//
1813// Test Buffer/Tensor
1814//===----------------------------------------------------------------------===//
1815
1816def RegionYieldOp : TEST_Op<"region_yield",
1817      [NoSideEffect, ReturnLike, Terminator]> {
1818  let description = [{
1819    This operation is used in a region and yields the corresponding type for
1820    that operation.
1821  }];
1822  let arguments = (ins AnyType:$result);
1823  let assemblyFormat = [{
1824    $result `:` type($result) attr-dict
1825  }];
1826  let builders = [OpBuilderDAG<(ins),
1827    [{ build($_builder, $_state, {}); }]>
1828  ];
1829}
1830
1831class BufferBasedOpBase<string mnemonic, list<OpTrait> traits>
1832    : TEST_Op<mnemonic, traits> {
1833  let description = [{
1834    A buffer based operation, that uses memRefs as input and output.
1835  }];
1836  let arguments = (ins AnyMemRef:$input, AnyMemRef:$output);
1837}
1838
1839def BufferBasedOp : BufferBasedOpBase<"buffer_based", []>{
1840  let assemblyFormat = [{
1841    `in` `(` $input`:` type($input) `)` `out` `(` $output`:` type($output) `)`
1842    attr-dict
1843  }];
1844}
1845
1846def RegionBufferBasedOp : BufferBasedOpBase<"region_buffer_based",
1847      [SingleBlockImplicitTerminator<"RegionYieldOp">]> {
1848  let regions = (region AnyRegion:$region);
1849  let assemblyFormat = [{
1850    `in` `(` $input`:` type($input) `)` `out` `(` $output`:` type($output) `)`
1851    $region attr-dict
1852  }];
1853}
1854
1855def TensorBasedOp : TEST_Op<"tensor_based", []> {
1856  let description = [{
1857    A tensor based operation, that uses a tensor as an input and results in a
1858    tensor again.
1859  }];
1860  let arguments = (ins AnyRankedTensor:$input);
1861  let results = (outs AnyRankedTensor:$result);
1862  let assemblyFormat = [{
1863    `in` `(` $input`:` type($input) `)` `->` type($result) attr-dict
1864  }];
1865}
1866
1867//===----------------------------------------------------------------------===//
1868// Test RegionBranchOpInterface
1869//===----------------------------------------------------------------------===//
1870
1871def RegionIfYieldOp : TEST_Op<"region_if_yield",
1872      [NoSideEffect, ReturnLike, Terminator]> {
1873  let arguments = (ins Variadic<AnyType>:$results);
1874  let assemblyFormat = [{
1875    $results `:` type($results) attr-dict
1876  }];
1877}
1878
1879def RegionIfOp : TEST_Op<"region_if",
1880      [DeclareOpInterfaceMethods<RegionBranchOpInterface>,
1881       SingleBlockImplicitTerminator<"RegionIfYieldOp">,
1882       RecursiveSideEffects]> {
1883  let description =[{
1884    Represents an abstract if-then-else-join pattern. In this context, the then
1885    and else regions jump to the join region, which finally returns to its
1886    parent op.
1887    }];
1888
1889  let printer = [{ return ::print(p, *this); }];
1890  let parser = [{ return ::parseRegionIfOp(parser, result); }];
1891  let arguments = (ins Variadic<AnyType>);
1892  let results = (outs Variadic<AnyType>:$results);
1893  let regions = (region SizedRegion<1>:$thenRegion,
1894                        AnyRegion:$elseRegion,
1895                        AnyRegion:$joinRegion);
1896  let extraClassDeclaration = [{
1897    Block::BlockArgListType getThenArgs() {
1898      return getBody(0)->getArguments();
1899    }
1900    Block::BlockArgListType getElseArgs() {
1901      return getBody(1)->getArguments();
1902    }
1903    Block::BlockArgListType getJoinArgs() {
1904      return getBody(2)->getArguments();
1905    }
1906    OperandRange getSuccessorEntryOperands(unsigned index);
1907  }];
1908}
1909
1910//===----------------------------------------------------------------------===//
1911// Test TableGen generated build() methods
1912//===----------------------------------------------------------------------===//
1913
1914def TableGenConstant : TEST_Op<"tblgen_constant"> {
1915  let results = (outs AnyType);
1916}
1917
1918// No variadic args or results.
1919def TableGenBuildOp0 : TEST_Op<"tblgen_build_0"> {
1920  let arguments = (ins AnyType:$value);
1921  let results = (outs AnyType:$result);
1922}
1923
1924// Sigle variadic arg and single variadic results.
1925def TableGenBuildOp1 : TEST_Op<"tblgen_build_1"> {
1926  let arguments = (ins Variadic<AnyType>:$inputs);
1927  let results = (outs Variadic<AnyType>:$results);
1928}
1929
1930// Single variadic arg and non-variadic results.
1931def TableGenBuildOp2 : TEST_Op<"tblgen_build_2"> {
1932  let arguments = (ins Variadic<AnyType>:$inputs);
1933  let results = (outs AnyType:$result);
1934}
1935
1936// Single variadic arg and multiple variadic results.
1937def TableGenBuildOp3 : TEST_Op<"tblgen_build_3", [SameVariadicResultSize]> {
1938  let arguments = (ins Variadic<AnyType>:$inputs);
1939  let results = (outs Variadic<AnyType>:$resultA, Variadic<AnyType>:$resultB);
1940}
1941
1942// Single variadic arg, non variadic results, with SameOperandsAndResultType.
1943// Tests suppression of ambiguous build methods for operations with
1944// SameOperandsAndResultType trait.
1945def TableGenBuildOp4 : TEST_Op<"tblgen_build_4", [SameOperandsAndResultType]> {
1946  let arguments = (ins Variadic<AnyType>:$inputs);
1947  let results = (outs AnyType:$result);
1948}
1949
1950// Single variadic arg with SameOperandsAndResultType and InferTypeOpInterface.
1951// Tests suppression of ambiguous build methods for operations with
1952// SameOperandsAndResultType and InferTypeOpInterface.
1953def TableGenBuildOp5 : TEST_Op<"tblgen_build_5",
1954      [SameOperandsAndResultType, InferTypeOpInterface]> {
1955  let arguments = (ins Variadic<AnyType>:$inputs);
1956  let results = (outs AnyType:$result);
1957
1958  let extraClassDeclaration = [{
1959    static LogicalResult inferReturnTypes(MLIRContext *,
1960          Optional<Location> location, ValueRange operands,
1961          DictionaryAttr attributes, RegionRange regions,
1962          SmallVectorImpl<Type> &inferredReturnTypes) {
1963      inferredReturnTypes.assign({operands[0].getType()});
1964      return success();
1965    }
1966   }];
1967}
1968
1969//===----------------------------------------------------------------------===//
1970// Test BufferPlacement
1971//===----------------------------------------------------------------------===//
1972
1973def GetTupleElementOp: TEST_Op<"get_tuple_element"> {
1974  let description = [{
1975    Test op that returns a specified element of the tuple.
1976  }];
1977
1978  let arguments = (ins
1979    TupleOf<[AnyType]>,
1980    I32Attr:$index
1981  );
1982  let results = (outs AnyType);
1983}
1984
1985def MakeTupleOp: TEST_Op<"make_tuple"> {
1986  let description = [{
1987    Test op that creates a tuple value from a list of values.
1988  }];
1989
1990  let arguments = (ins
1991    Variadic<AnyType>:$inputs
1992  );
1993  let results = (outs TupleOf<[AnyType]>);
1994}
1995
1996#endif // TEST_OPS
1997