/
LLVMOps.td
1881 lines (1667 loc) · 69.2 KB
/
LLVMOps.td
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===-- LLVMOps.td - LLVM IR dialect op definition file ----*- tablegen -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This is the LLVM IR operation definition file.
//
//===----------------------------------------------------------------------===//
#ifndef LLVMIR_OPS
#define LLVMIR_OPS
include "mlir/Dialect/LLVMIR/LLVMAttrDefs.td"
include "mlir/Dialect/LLVMIR/LLVMOpBase.td"
include "mlir/IR/EnumAttr.td"
include "mlir/IR/FunctionInterfaces.td"
include "mlir/IR/SymbolInterfaces.td"
include "mlir/Interfaces/CallInterfaces.td"
include "mlir/Interfaces/ControlFlowInterfaces.td"
include "mlir/Interfaces/InferTypeOpInterface.td"
include "mlir/Interfaces/SideEffectInterfaces.td"
class LLVM_Builder<string builder> {
string llvmBuilder = builder;
}
// Base class for LLVM terminator operations. All terminator operations have
// zero results and an optional list of successors.
class LLVM_TerminatorOp<string mnemonic, list<Trait> traits = []> :
LLVM_Op<mnemonic, !listconcat(traits, [Terminator])>;
// Class for arithmetic binary operations.
class LLVM_ArithmeticOpBase<Type type, string mnemonic,
string instName, list<Trait> traits = []> :
LLVM_Op<mnemonic,
!listconcat([Pure, SameOperandsAndResultType], traits)>,
LLVM_Builder<"$res = builder.Create" # instName # "($lhs, $rhs);"> {
dag commonArgs = (ins LLVM_ScalarOrVectorOf<type>:$lhs,
LLVM_ScalarOrVectorOf<type>:$rhs);
let results = (outs LLVM_ScalarOrVectorOf<type>:$res);
let builders = [LLVM_OneResultOpBuilder];
let assemblyFormat = "$lhs `,` $rhs custom<LLVMOpAttrs>(attr-dict) `:` type($res)";
string llvmInstName = instName;
}
class LLVM_IntArithmeticOp<string mnemonic, string instName,
list<Trait> traits = []> :
LLVM_ArithmeticOpBase<AnyInteger, mnemonic, instName, traits> {
let arguments = commonArgs;
string mlirBuilder = [{
$res = $_builder.create<$_qualCppClassName>($_location, $lhs, $rhs);
}];
}
class LLVM_FloatArithmeticOp<string mnemonic, string instName,
list<Trait> traits = []> :
LLVM_ArithmeticOpBase<LLVM_AnyFloat, mnemonic, instName,
!listconcat([DeclareOpInterfaceMethods<FastmathFlagsInterface>], traits)> {
dag fmfArg = (
ins DefaultValuedAttr<LLVM_FastmathFlagsAttr, "{}">:$fastmathFlags);
let arguments = !con(commonArgs, fmfArg);
string mlirBuilder = [{
auto op = $_builder.create<$_qualCppClassName>($_location, $lhs, $rhs);
moduleImport.setFastmathFlagsAttr(inst, op);
$res = op;
}];
}
// Class for arithmetic unary operations.
class LLVM_UnaryFloatArithmeticOp<Type type, string mnemonic,
string instName, list<Trait> traits = []> :
LLVM_Op<mnemonic,
!listconcat([Pure, SameOperandsAndResultType, DeclareOpInterfaceMethods<FastmathFlagsInterface>], traits)>,
LLVM_Builder<"$res = builder.Create" # instName # "($operand);"> {
let arguments = (
ins type:$operand,
DefaultValuedAttr<LLVM_FastmathFlagsAttr, "{}">:$fastmathFlags);
let results = (outs type:$res);
let builders = [LLVM_OneResultOpBuilder];
let assemblyFormat = "$operand custom<LLVMOpAttrs>(attr-dict) `:` type($res)";
string llvmInstName = instName;
string mlirBuilder = [{
auto op = $_builder.create<$_qualCppClassName>($_location, $operand);
moduleImport.setFastmathFlagsAttr(inst, op);
$res = op;
}];
}
// Integer binary operations.
def LLVM_AddOp : LLVM_IntArithmeticOp<"add", "Add", [Commutative]>;
def LLVM_SubOp : LLVM_IntArithmeticOp<"sub", "Sub">;
def LLVM_MulOp : LLVM_IntArithmeticOp<"mul", "Mul", [Commutative]>;
def LLVM_UDivOp : LLVM_IntArithmeticOp<"udiv", "UDiv">;
def LLVM_SDivOp : LLVM_IntArithmeticOp<"sdiv", "SDiv">;
def LLVM_URemOp : LLVM_IntArithmeticOp<"urem", "URem">;
def LLVM_SRemOp : LLVM_IntArithmeticOp<"srem", "SRem">;
def LLVM_AndOp : LLVM_IntArithmeticOp<"and", "And">;
def LLVM_OrOp : LLVM_IntArithmeticOp<"or", "Or">;
def LLVM_XOrOp : LLVM_IntArithmeticOp<"xor", "Xor">;
def LLVM_ShlOp : LLVM_IntArithmeticOp<"shl", "Shl">;
def LLVM_LShrOp : LLVM_IntArithmeticOp<"lshr", "LShr">;
def LLVM_AShrOp : LLVM_IntArithmeticOp<"ashr", "AShr">;
// Base class for compare operations. A compare operation takes two operands
// of the same type and returns a boolean result. If the operands are
// vectors, then the result has to be a boolean vector of the same shape.
class LLVM_ArithmeticCmpOp<string mnemonic, list<Trait> traits = []> :
LLVM_Op<mnemonic, traits # [SameTypeOperands, TypesMatchWith<
"result type has i1 element type and same shape as operands",
"lhs", "res", "::getI1SameShape($_self)">]> {
let results = (outs LLVM_ScalarOrVectorOf<I1>:$res);
}
// Other integer operations.
def LLVM_ICmpOp : LLVM_ArithmeticCmpOp<"icmp", [Pure]> {
let arguments = (ins ICmpPredicate:$predicate,
AnyTypeOf<[LLVM_ScalarOrVectorOf<AnyInteger>,
LLVM_ScalarOrVectorOf<LLVM_AnyPointer>]>:$lhs,
AnyTypeOf<[LLVM_ScalarOrVectorOf<AnyInteger>,
LLVM_ScalarOrVectorOf<LLVM_AnyPointer>]>:$rhs);
let hasCustomAssemblyFormat = 1;
string llvmInstName = "ICmp";
string llvmBuilder = [{
$res = builder.CreateICmp(
convertICmpPredicateToLLVM($predicate), $lhs, $rhs);
}];
string mlirBuilder = [{
auto *iCmpInst = cast<llvm::ICmpInst>(inst);
$res = $_builder.create<$_qualCppClassName>($_location,
convertICmpPredicateFromLLVM(iCmpInst->getPredicate()), $lhs, $rhs);
}];
// Set the $predicate index to -1 to indicate there is no matching operand
// and decrement the following indices.
list<int> llvmArgIndices = [-1, 0, 1];
}
// Other floating-point operations.
def LLVM_FCmpOp : LLVM_ArithmeticCmpOp<"fcmp", [
Pure, DeclareOpInterfaceMethods<FastmathFlagsInterface>]> {
let arguments = (ins FCmpPredicate:$predicate,
LLVM_ScalarOrVectorOf<LLVM_AnyFloat>:$lhs,
LLVM_ScalarOrVectorOf<LLVM_AnyFloat>:$rhs,
DefaultValuedAttr<LLVM_FastmathFlagsAttr,
"{}">:$fastmathFlags);
let hasCustomAssemblyFormat = 1;
string llvmInstName = "FCmp";
string llvmBuilder = [{
$res = builder.CreateFCmp(convertFCmpPredicateToLLVM($predicate), $lhs, $rhs);
}];
string mlirBuilder = [{
auto *fCmpInst = cast<llvm::FCmpInst>(inst);
auto op = $_builder.create<$_qualCppClassName>(
$_location, convertFCmpPredicateFromLLVM(fCmpInst->getPredicate()), $lhs, $rhs);
moduleImport.setFastmathFlagsAttr(inst, op);
$res = op;
}];
// Set the $predicate index to -1 to indicate there is no matching operand
// and decrement the following indices.
list<int> llvmArgIndices = [-1, 0, 1, 2];
}
// Floating point binary operations.
def LLVM_FAddOp : LLVM_FloatArithmeticOp<"fadd", "FAdd">;
def LLVM_FSubOp : LLVM_FloatArithmeticOp<"fsub", "FSub">;
def LLVM_FMulOp : LLVM_FloatArithmeticOp<"fmul", "FMul">;
def LLVM_FDivOp : LLVM_FloatArithmeticOp<"fdiv", "FDiv">;
def LLVM_FRemOp : LLVM_FloatArithmeticOp<"frem", "FRem">;
def LLVM_FNegOp : LLVM_UnaryFloatArithmeticOp<
LLVM_ScalarOrVectorOf<LLVM_AnyFloat>, "fneg", "FNeg">;
// Memory-related operations.
def LLVM_AllocaOp : LLVM_Op<"alloca">, LLVM_MemOpPatterns {
let arguments = (ins AnyInteger:$arraySize,
OptionalAttr<I64Attr>:$alignment,
OptionalAttr<TypeAttr>:$elem_type,
UnitAttr:$inalloca);
let results = (outs Res<LLVM_AnyPointer, "",
[MemAlloc<AutomaticAllocationScopeResource>]>:$res);
string llvmInstName = "Alloca";
string llvmBuilder = [{
auto addrSpace = $_resultType->getPointerAddressSpace();
llvm::Type *elementType = moduleTranslation.convertType(
$elem_type ? *$elem_type
: op.getType().cast<LLVMPointerType>().getElementType());
auto *inst = builder.CreateAlloca(elementType, addrSpace, $arraySize);
}] # setAlignmentCode # [{
inst->setUsedWithInAlloca($inalloca);
$res = inst;
}];
string mlirBuilder = [{
auto *allocaInst = cast<llvm::AllocaInst>(inst);
Type allocatedType =
moduleImport.convertType(allocaInst->getAllocatedType());
unsigned alignment = allocaInst->getAlign().value();
$res = $_builder.create<LLVM::AllocaOp>(
$_location, $_resultType, $arraySize,
alignment == 0 ? IntegerAttr() : $_builder.getI64IntegerAttr(alignment),
TypeAttr::get(allocatedType), allocaInst->isUsedWithInAlloca());
}];
let builders = [
OpBuilder<(ins "Type":$resultType, "Value":$arraySize,
"unsigned":$alignment),
[{
assert(!resultType.cast<LLVMPointerType>().isOpaque() &&
"pass the allocated type explicitly if opaque pointers are used");
if (alignment == 0)
return build($_builder, $_state, resultType, arraySize, IntegerAttr(),
TypeAttr(), false);
build($_builder, $_state, resultType, arraySize,
$_builder.getI64IntegerAttr(alignment), TypeAttr(), false);
}]>,
OpBuilder<(ins "Type":$resultType, "Type":$elementType, "Value":$arraySize,
CArg<"unsigned", "0">:$alignment),
[{
TypeAttr elemTypeAttr =
resultType.cast<LLVMPointerType>().isOpaque() ?
TypeAttr::get(elementType) : TypeAttr();
build($_builder, $_state, resultType, arraySize,
alignment == 0 ? IntegerAttr()
: $_builder.getI64IntegerAttr(alignment),
elemTypeAttr, false);
}]>
];
let hasCustomAssemblyFormat = 1;
let hasVerifier = 1;
}
def LLVM_GEPOp : LLVM_Op<"getelementptr", [Pure]> {
let arguments = (ins LLVM_ScalarOrVectorOf<LLVM_AnyPointer>:$base,
Variadic<LLVM_ScalarOrVectorOf<AnyInteger>>:$dynamicIndices,
DenseI32ArrayAttr:$rawConstantIndices,
OptionalAttr<TypeAttr>:$elem_type,
UnitAttr:$inbounds);
let results = (outs LLVM_ScalarOrVectorOf<LLVM_AnyPointer>:$res);
let skipDefaultBuilders = 1;
let description = [{
This operation mirrors LLVM IRs 'getelementptr' operation that is used to
perform pointer arithmetic.
Like in LLVM IR, it is possible to use both constants as well as SSA values
as indices. In the case of indexing within a structure, it is required to
either use constant indices directly, or supply a constant SSA value.
An optional 'inbounds' attribute specifies the low-level pointer arithmetic
overflow behavior that LLVM uses after lowering the operation to LLVM IR.
Examples:
```mlir
// GEP with an SSA value offset
%0 = llvm.getelementptr %1[%2] : (!llvm.ptr<f32>, i64) -> !llvm.ptr<f32>
// GEP with a constant offset and the inbounds attribute set
%0 = llvm.getelementptr inbounds %1[3] : (!llvm.ptr<f32>) -> !llvm.ptr<f32>
// GEP with constant offsets into a structure
%0 = llvm.getelementptr %1[0, 1]
: (!llvm.ptr<struct(i32, f32)>) -> !llvm.ptr<f32>
```
}];
let builders = [
OpBuilder<(ins "Type":$resultType, "Type":$basePtrType, "Value":$basePtr,
"ValueRange":$indices, CArg<"bool", "false">:$inbounds,
CArg<"ArrayRef<NamedAttribute>", "{}">:$attributes)>,
OpBuilder<(ins "Type":$resultType, "Value":$basePtr,
"ValueRange":$indices, CArg<"bool", "false">:$inbounds,
CArg<"ArrayRef<NamedAttribute>", "{}">:$attributes)>,
OpBuilder<(ins "Type":$resultType, "Value":$basePtr,
"ArrayRef<GEPArg>":$indices, CArg<"bool", "false">:$inbounds,
CArg<"ArrayRef<NamedAttribute>", "{}">:$attributes)>,
OpBuilder<(ins "Type":$resultType, "Type":$basePtrType, "Value":$basePtr,
"ArrayRef<GEPArg>":$indices, CArg<"bool", "false">:$inbounds,
CArg<"ArrayRef<NamedAttribute>", "{}">:$attributes)>,
];
let llvmBuilder = [{
SmallVector<llvm::Value *> indices;
indices.reserve($rawConstantIndices.size());
GEPIndicesAdaptor<decltype($dynamicIndices)>
gepIndices(op.getRawConstantIndicesAttr(), $dynamicIndices);
for (PointerUnion<IntegerAttr, llvm::Value*> valueOrAttr : gepIndices) {
if (llvm::Value* value = valueOrAttr.dyn_cast<llvm::Value*>())
indices.push_back(value);
else
indices.push_back(
builder.getInt32(valueOrAttr.get<IntegerAttr>().getInt()));
}
Type baseElementType = op.getSourceElementType();
llvm::Type *elementType = moduleTranslation.convertType(baseElementType);
$res = builder.CreateGEP(elementType, $base, indices, "", $inbounds);
}];
let assemblyFormat = [{
(`inbounds` $inbounds^)?
$base `[` custom<GEPIndices>($dynamicIndices, $rawConstantIndices) `]` attr-dict
`:` functional-type(operands, results) (`,` $elem_type^)?
}];
let extraClassDeclaration = [{
constexpr static int32_t kDynamicIndex = std::numeric_limits<int32_t>::min();
/// Returns the type pointed to by the pointer argument of this GEP.
Type getSourceElementType();
GEPIndicesAdaptor<ValueRange> getIndices();
}];
let hasFolder = 1;
let hasVerifier = 1;
}
def LLVM_LoadOp : LLVM_MemAccessOpBase<"load"> {
dag args = (ins Arg<LLVM_PointerTo<LLVM_LoadableType>, "", [MemRead]>:$addr,
OptionalAttr<I64Attr>:$alignment,
UnitAttr:$volatile_,
UnitAttr:$nontemporal,
DefaultValuedAttr<
AtomicOrdering, "AtomicOrdering::not_atomic">:$ordering,
OptionalAttr<StrAttr>:$syncscope);
// Append the aliasing related attributes define in LLVM_MemAccessOpBase.
let arguments = !con(args, aliasAttrs);
let results = (outs LLVM_LoadableType:$res);
string llvmInstName = "Load";
let description = [{
The `load` operation is used to read from memory. A load may be marked as
atomic, volatile, and/or nontemporal, and takes a number of optional
attributes that specify aliasing information.
An atomic load only supports a limited set of pointer, integer, and
floating point types, and requires an explicit alignment.
Examples:
```mlir
// A volatile load of a float variable.
%0 = llvm.load volatile %ptr : !llvm.ptr -> f32
// A nontemporal load of a float variable.
%0 = llvm.load %ptr {nontemporal} : !llvm.ptr -> f32
// An atomic load of an integer variable.
%0 = llvm.load %ptr atomic monotonic {alignment = 8 : i64}
: !llvm.ptr -> i64
```
See the following link for more details:
https://llvm.org/docs/LangRef.html#load-instruction
}];
let assemblyFormat = [{
(`volatile` $volatile_^)? $addr
(`atomic` (`syncscope` `(` $syncscope^ `)`)? $ordering^)?
attr-dict `:` custom<LoadType>(type($addr), type($res))
}];
string llvmBuilder = [{
auto *inst = builder.CreateLoad($_resultType, $addr, $volatile_);
$res = inst;
}] # setOrderingCode
# setSyncScopeCode
# setAlignmentCode
# setNonTemporalMetadataCode
# setAccessGroupsMetadataCode
# setAliasAnalysisMetadataCode;
string mlirBuilder = [{
auto *loadInst = cast<llvm::LoadInst>(inst);
unsigned alignment = loadInst->getAlign().value();
$res = $_builder.create<LLVM::LoadOp>($_location, $_resultType, $addr,
alignment, loadInst->isVolatile(),
loadInst->hasMetadata(llvm::LLVMContext::MD_nontemporal),
convertAtomicOrderingFromLLVM(loadInst->getOrdering()),
getLLVMSyncScope(loadInst));
}];
let builders = [
OpBuilder<(ins "Value":$addr, CArg<"unsigned", "0">:$alignment,
CArg<"bool", "false">:$isVolatile, CArg<"bool", "false">:$isNonTemporal)>,
OpBuilder<(ins "Type":$type, "Value":$addr,
CArg<"unsigned", "0">:$alignment, CArg<"bool", "false">:$isVolatile,
CArg<"bool", "false">:$isNonTemporal,
CArg<"AtomicOrdering", "AtomicOrdering::not_atomic">:$ordering,
CArg<"StringRef", "StringRef()">:$syncscope)>
];
let hasVerifier = 1;
}
def LLVM_StoreOp : LLVM_MemAccessOpBase<"store"> {
dag args = (ins LLVM_LoadableType:$value,
Arg<LLVM_PointerTo<LLVM_LoadableType>,"",[MemWrite]>:$addr,
OptionalAttr<I64Attr>:$alignment,
UnitAttr:$volatile_,
UnitAttr:$nontemporal,
DefaultValuedAttr<
AtomicOrdering, "AtomicOrdering::not_atomic">:$ordering,
OptionalAttr<StrAttr>:$syncscope);
// Append the aliasing related attributes define in LLVM_MemAccessOpBase.
let arguments = !con(args, aliasAttrs);
string llvmInstName = "Store";
let description = [{
The `store` operation is used to write to memory. A store may be marked as
atomic, volatile, and/or nontemporal, and takes a number of optional
attributes that specify aliasing information.
An atomic store only supports a limited set of pointer, integer, and
floating point types, and requires an explicit alignment.
Examples:
```mlir
// A volatile store of a float variable.
llvm.store volatile %val, %ptr : f32, !llvm.ptr
// A nontemporal store of a float variable.
llvm.store %val, %ptr {nontemporal} : f32, !llvm.ptr
// An atomic store of an integer variable.
llvm.store %val, %ptr atomic monotonic {alignment = 8 : i64}
: i64, !llvm.ptr
```
See the following link for more details:
https://llvm.org/docs/LangRef.html#store-instruction
}];
let assemblyFormat = [{
(`volatile` $volatile_^)? $value `,` $addr
(`atomic` (`syncscope` `(` $syncscope^ `)`)? $ordering^)?
attr-dict `:` custom<StoreType>(type($value), type($addr))
}];
string llvmBuilder = [{
auto *inst = builder.CreateStore($value, $addr, $volatile_);
}] # setOrderingCode
# setSyncScopeCode
# setAlignmentCode
# setNonTemporalMetadataCode
# setAccessGroupsMetadataCode
# setAliasAnalysisMetadataCode;
string mlirBuilder = [{
auto *storeInst = cast<llvm::StoreInst>(inst);
unsigned alignment = storeInst->getAlign().value();
$_op = $_builder.create<LLVM::StoreOp>($_location, $value, $addr,
alignment, storeInst->isVolatile(),
storeInst->hasMetadata(llvm::LLVMContext::MD_nontemporal),
convertAtomicOrderingFromLLVM(storeInst->getOrdering()),
getLLVMSyncScope(storeInst));
}];
let builders = [
OpBuilder<(ins "Value":$value, "Value":$addr,
CArg<"unsigned", "0">:$alignment, CArg<"bool", "false">:$isVolatile,
CArg<"bool", "false">:$isNonTemporal,
CArg<"AtomicOrdering", "AtomicOrdering::not_atomic">:$ordering,
CArg<"StringRef", "StringRef()">:$syncscope)>
];
let hasVerifier = 1;
}
// Casts.
class LLVM_CastOp<string mnemonic, string instName, Type type,
Type resultType, list<Trait> traits = []> :
LLVM_Op<mnemonic, !listconcat([Pure], traits)>,
LLVM_Builder<"$res = builder.Create" # instName # "($arg, $_resultType);"> {
let arguments = (ins type:$arg);
let results = (outs resultType:$res);
let builders = [LLVM_OneResultOpBuilder];
let assemblyFormat = "$arg attr-dict `:` type($arg) `to` type($res)";
string llvmInstName = instName;
string mlirBuilder = [{
$res = $_builder.create<$_qualCppClassName>(
$_location, $_resultType, $arg);
}];
}
def LLVM_BitcastOp : LLVM_CastOp<"bitcast", "BitCast",
LLVM_AnyNonAggregate, LLVM_AnyNonAggregate> {
let hasFolder = 1;
let hasVerifier = 1;
}
def LLVM_AddrSpaceCastOp : LLVM_CastOp<"addrspacecast", "AddrSpaceCast",
LLVM_ScalarOrVectorOf<LLVM_AnyPointer>,
LLVM_ScalarOrVectorOf<LLVM_AnyPointer>> {
let hasFolder = 1;
}
def LLVM_IntToPtrOp : LLVM_CastOp<"inttoptr", "IntToPtr",
LLVM_ScalarOrVectorOf<AnyInteger>,
LLVM_ScalarOrVectorOf<LLVM_AnyPointer>>;
def LLVM_PtrToIntOp : LLVM_CastOp<"ptrtoint", "PtrToInt",
LLVM_ScalarOrVectorOf<LLVM_AnyPointer>,
LLVM_ScalarOrVectorOf<AnyInteger>>;
def LLVM_SExtOp : LLVM_CastOp<"sext", "SExt",
LLVM_ScalarOrVectorOf<AnyInteger>,
LLVM_ScalarOrVectorOf<AnyInteger>>;
def LLVM_ZExtOp : LLVM_CastOp<"zext", "ZExt",
LLVM_ScalarOrVectorOf<AnyInteger>,
LLVM_ScalarOrVectorOf<AnyInteger>>;
def LLVM_TruncOp : LLVM_CastOp<"trunc", "Trunc",
LLVM_ScalarOrVectorOf<AnyInteger>,
LLVM_ScalarOrVectorOf<AnyInteger>>;
def LLVM_SIToFPOp : LLVM_CastOp<"sitofp", "SIToFP",
LLVM_ScalarOrVectorOf<AnyInteger>,
LLVM_ScalarOrVectorOf<LLVM_AnyFloat>>;
def LLVM_UIToFPOp : LLVM_CastOp<"uitofp", "UIToFP",
LLVM_ScalarOrVectorOf<AnyInteger>,
LLVM_ScalarOrVectorOf<LLVM_AnyFloat>>;
def LLVM_FPToSIOp : LLVM_CastOp<"fptosi", "FPToSI",
LLVM_ScalarOrVectorOf<LLVM_AnyFloat>,
LLVM_ScalarOrVectorOf<AnyInteger>>;
def LLVM_FPToUIOp : LLVM_CastOp<"fptoui", "FPToUI",
LLVM_ScalarOrVectorOf<LLVM_AnyFloat>,
LLVM_ScalarOrVectorOf<AnyInteger>>;
def LLVM_FPExtOp : LLVM_CastOp<"fpext", "FPExt",
LLVM_ScalarOrVectorOf<LLVM_AnyFloat>,
LLVM_ScalarOrVectorOf<LLVM_AnyFloat>>;
def LLVM_FPTruncOp : LLVM_CastOp<"fptrunc", "FPTrunc",
LLVM_ScalarOrVectorOf<LLVM_AnyFloat>,
LLVM_ScalarOrVectorOf<LLVM_AnyFloat>>;
// Call-related operations.
def LLVM_InvokeOp : LLVM_Op<"invoke", [
AttrSizedOperandSegments,
DeclareOpInterfaceMethods<BranchOpInterface>,
DeclareOpInterfaceMethods<CallOpInterface>, Terminator]> {
let arguments = (ins OptionalAttr<FlatSymbolRefAttr>:$callee,
Variadic<LLVM_Type>:$callee_operands,
Variadic<LLVM_Type>:$normalDestOperands,
Variadic<LLVM_Type>:$unwindDestOperands,
OptionalAttr<ElementsAttr>:$branch_weights);
let results = (outs Variadic<LLVM_Type>);
let successors = (successor AnySuccessor:$normalDest,
AnySuccessor:$unwindDest);
let builders = [
OpBuilder<(ins "TypeRange":$tys, "FlatSymbolRefAttr":$callee,
"ValueRange":$ops, "Block*":$normal, "ValueRange":$normalOps,
"Block*":$unwind, "ValueRange":$unwindOps),
[{
$_state.addAttribute("callee", callee);
build($_builder, $_state, tys, ops, normal, normalOps, unwind, unwindOps);
}]>,
OpBuilder<(ins "TypeRange":$tys, "ValueRange":$ops, "Block*":$normal,
"ValueRange":$normalOps, "Block*":$unwind, "ValueRange":$unwindOps),
[{
build($_builder, $_state, tys, /*callee=*/FlatSymbolRefAttr(), ops, normalOps,
unwindOps, nullptr, normal, unwind);
}]>];
let hasCustomAssemblyFormat = 1;
let hasVerifier = 1;
}
def LLVM_LandingpadOp : LLVM_Op<"landingpad"> {
let arguments = (ins UnitAttr:$cleanup, Variadic<LLVM_Type>);
let results = (outs LLVM_Type:$res);
let builders = [LLVM_OneResultOpBuilder];
let hasCustomAssemblyFormat = 1;
let hasVerifier = 1;
}
//===----------------------------------------------------------------------===//
// CallOp
//===----------------------------------------------------------------------===//
// FIXME: Add a type attribute that carries the LLVM function type to support
// indirect calls to variadic functions. The type attribute is necessary to
// distinguish normal and variadic arguments.
def LLVM_CallOp : LLVM_Op<"call",
[DeclareOpInterfaceMethods<FastmathFlagsInterface>,
DeclareOpInterfaceMethods<CallOpInterface>,
DeclareOpInterfaceMethods<SymbolUserOpInterface>]> {
let summary = "Call to an LLVM function.";
let description = [{
In LLVM IR, functions may return either 0 or 1 value. LLVM IR dialect
implements this behavior by providing a variadic `call` operation for 0- and
1-result functions. Even though MLIR supports multi-result functions, LLVM
IR dialect disallows them.
The `call` instruction supports both direct and indirect calls. Direct calls
start with a function name (`@`-prefixed) and indirect calls start with an
SSA value (`%`-prefixed). The direct callee, if present, is stored as a
function attribute `callee`. The trailing type list contains the optional
indirect callee type and the MLIR function type, which differs from the
LLVM function type that uses a explicit void type to model functions that do
not return a value.
Examples:
```mlir
// Direct call without arguments and with one result.
%0 = llvm.call @foo() : () -> (f32)
// Direct call with arguments and without a result.
llvm.call @bar(%0) : (f32) -> ()
// Indirect call with an argument and without a result.
llvm.call %1(%0) : !llvm.ptr, (f32) -> ()
```
}];
let arguments = (ins OptionalAttr<FlatSymbolRefAttr>:$callee,
Variadic<LLVM_Type>,
DefaultValuedAttr<LLVM_FastmathFlagsAttr,
"{}">:$fastmathFlags,
OptionalAttr<ElementsAttr>:$branch_weights);
let results = (outs Optional<LLVM_Type>:$result);
let builders = [
OpBuilder<(ins "LLVMFuncOp":$func, "ValueRange":$args)>,
OpBuilder<(ins "TypeRange":$results, "StringAttr":$callee,
CArg<"ValueRange", "{}">:$args)>,
OpBuilder<(ins "TypeRange":$results, "FlatSymbolRefAttr":$callee,
CArg<"ValueRange", "{}">:$args)>,
OpBuilder<(ins "TypeRange":$results, "StringRef":$callee,
CArg<"ValueRange", "{}">:$args)>
];
let hasCustomAssemblyFormat = 1;
}
//===----------------------------------------------------------------------===//
// ExtractElementOp
//===----------------------------------------------------------------------===//
def LLVM_ExtractElementOp : LLVM_Op<"extractelement", [Pure,
TypesMatchWith<"result type matches vector element type", "vector", "res",
"LLVM::getVectorElementType($_self)">]> {
let summary = "Extract an element from an LLVM vector.";
let arguments = (ins LLVM_AnyVector:$vector, AnyInteger:$position);
let results = (outs LLVM_Type:$res);
let assemblyFormat = [{
$vector `[` $position `:` type($position) `]` attr-dict `:` type($vector)
}];
string llvmInstName = "ExtractElement";
string llvmBuilder = [{
$res = builder.CreateExtractElement($vector, $position);
}];
string mlirBuilder = [{
$res = $_builder.create<LLVM::ExtractElementOp>(
$_location, $vector, $position);
}];
}
//===----------------------------------------------------------------------===//
// ExtractValueOp
//===----------------------------------------------------------------------===//
def LLVM_ExtractValueOp : LLVM_Op<"extractvalue", [Pure]> {
let summary = "Extract a value from an LLVM struct.";
let arguments = (ins LLVM_AnyAggregate:$container, DenseI64ArrayAttr:$position);
let results = (outs LLVM_Type:$res);
let builders = [
OpBuilder<(ins "Value":$container, "ArrayRef<int64_t>":$position)>
];
let assemblyFormat = [{
$container `` $position attr-dict `:` type($container)
custom<InsertExtractValueElementType>(type($res), ref(type($container)),
ref($position))
}];
let hasFolder = 1;
let hasVerifier = 1;
string llvmInstName = "ExtractValue";
string llvmBuilder = [{
$res = builder.CreateExtractValue($container, extractPosition($position));
}];
string mlirBuilder = [{
auto *evInst = cast<llvm::ExtractValueInst>(inst);
$res = $_builder.create<LLVM::ExtractValueOp>($_location,
$container, getPositionFromIndices(evInst->getIndices()));
}];
}
//===----------------------------------------------------------------------===//
// InsertElementOp
//===----------------------------------------------------------------------===//
def LLVM_InsertElementOp : LLVM_Op<"insertelement", [Pure,
TypesMatchWith<"argument type matches vector element type", "vector",
"value", "LLVM::getVectorElementType($_self)">,
AllTypesMatch<["res", "vector"]>]> {
let summary = "Insert an element into an LLVM vector.";
let arguments = (ins LLVM_AnyVector:$vector, LLVM_PrimitiveType:$value,
AnyInteger:$position);
let results = (outs LLVM_AnyVector:$res);
let builders = [LLVM_OneResultOpBuilder];
let assemblyFormat = [{
$value `,` $vector `[` $position `:` type($position) `]` attr-dict `:`
type($vector)
}];
string llvmInstName = "InsertElement";
string llvmBuilder = [{
$res = builder.CreateInsertElement($vector, $value, $position);
}];
string mlirBuilder = [{
$res = $_builder.create<LLVM::InsertElementOp>(
$_location, $vector, $value, $position);
}];
}
//===----------------------------------------------------------------------===//
// InsertValueOp
//===----------------------------------------------------------------------===//
def LLVM_InsertValueOp : LLVM_Op<
"insertvalue", [Pure, AllTypesMatch<["container", "res"]>]> {
let summary = "Insert a value into an LLVM struct.";
let arguments = (ins LLVM_AnyAggregate:$container, LLVM_PrimitiveType:$value,
DenseI64ArrayAttr:$position);
let results = (outs LLVM_AnyAggregate:$res);
let assemblyFormat = [{
$value `,` $container `` $position attr-dict `:` type($container)
custom<InsertExtractValueElementType>(type($value), ref(type($container)),
ref($position))
}];
let hasVerifier = 1;
string llvmInstName = "InsertValue";
string llvmBuilder = [{
$res = builder.CreateInsertValue($container, $value,
extractPosition($position));
}];
string mlirBuilder = [{
auto *ivInst = cast<llvm::InsertValueInst>(inst);
$res = $_builder.create<LLVM::InsertValueOp>($_location,
$container, $value, getPositionFromIndices(ivInst->getIndices()));
}];
}
//===----------------------------------------------------------------------===//
// ShuffleVectorOp
//===----------------------------------------------------------------------===//
def LLVM_ShuffleVectorOp : LLVM_Op<"shufflevector",
[Pure, AllTypesMatch<["v1", "v2"]>]> {
let summary = "Construct a permutation of two vectors.";
let arguments = (ins LLVM_AnyVector:$v1, LLVM_AnyVector:$v2,
DenseI32ArrayAttr:$mask);
let results = (outs LLVM_AnyVector:$res);
let builders = [
OpBuilder<(ins "Value":$v1, "Value":$v2, "DenseI32ArrayAttr":$mask,
CArg<"ArrayRef<NamedAttribute>", "{}">:$attrs)>,
OpBuilder<(ins "Value":$v1, "Value":$v2, "ArrayRef<int32_t>":$mask)>
];
let assemblyFormat = [{
$v1 `,` $v2 $mask attr-dict `:` type($v1)
custom<ShuffleType>(ref(type($v1)), type($res), ref($mask))
}];
let hasVerifier = 1;
string llvmInstName = "ShuffleVector";
string llvmBuilder = [{
$res = builder.CreateShuffleVector($v1, $v2, $mask);
}];
string mlirBuilder = [{
auto *svInst = cast<llvm::ShuffleVectorInst>(inst);
SmallVector<int32_t> mask(svInst->getShuffleMask());
$res = $_builder.create<LLVM::ShuffleVectorOp>(
$_location, $v1, $v2, mask);
}];
}
// Misc operations.
def LLVM_SelectOp
: LLVM_Op<"select",
[Pure, AllTypesMatch<["trueValue", "falseValue", "res"]>]>,
LLVM_Builder<
"$res = builder.CreateSelect($condition, $trueValue, $falseValue);"> {
let arguments = (ins LLVM_ScalarOrVectorOf<I1>:$condition,
LLVM_Type:$trueValue, LLVM_Type:$falseValue);
let results = (outs LLVM_Type:$res);
let assemblyFormat = "operands attr-dict `:` type($condition) `,` type($res)";
string llvmInstName = "Select";
string mlirBuilder = [{
$res = $_builder.create<LLVM::SelectOp>(
$_location, $_resultType, $condition, $trueValue, $falseValue);
}];
}
def LLVM_FreezeOp : LLVM_Op<"freeze", [SameOperandsAndResultType]> {
let arguments = (ins LLVM_Type:$val);
let results = (outs LLVM_Type:$res);
let builders = [LLVM_OneResultOpBuilder];
let assemblyFormat = "$val attr-dict `:` type($val)";
string llvmInstName = "Freeze";
string llvmBuilder = "$res = builder.CreateFreeze($val);";
string mlirBuilder = [{
$res = $_builder.create<LLVM::FreezeOp>($_location, $val);
}];
}
// Terminators.
def LLVM_BrOp : LLVM_TerminatorOp<"br",
[DeclareOpInterfaceMethods<BranchOpInterface>, Pure]> {
let arguments = (ins
Variadic<LLVM_Type>:$destOperands,
OptionalAttr<LoopAnnotationAttr>:$loop_annotation
);
let successors = (successor AnySuccessor:$dest);
let assemblyFormat = [{
$dest (`(` $destOperands^ `:` type($destOperands) `)`)? attr-dict
}];
let builders = [
OpBuilder<(ins "Block *":$dest), [{
build($_builder, $_state, ValueRange(), dest);
}]>,
OpBuilder<(ins "ValueRange":$operands, "Block *":$dest), [{
build($_builder, $_state, operands, /*loop_annotation=*/{}, dest);
}]>,
LLVM_TerminatorPassthroughOpBuilder
];
let hasVerifier = 1;
}
def LLVM_CondBrOp : LLVM_TerminatorOp<"cond_br",
[AttrSizedOperandSegments, DeclareOpInterfaceMethods<BranchOpInterface>,
Pure]> {
let arguments = (ins I1:$condition,
Variadic<LLVM_Type>:$trueDestOperands,
Variadic<LLVM_Type>:$falseDestOperands,
OptionalAttr<ElementsAttr>:$branch_weights,
OptionalAttr<LoopAnnotationAttr>:$loop_annotation);
let successors = (successor AnySuccessor:$trueDest, AnySuccessor:$falseDest);
let assemblyFormat = [{
$condition ( `weights` `(` $branch_weights^ `)` )? `,`
$trueDest (`(` $trueDestOperands^ `:` type($trueDestOperands) `)`)? `,`
$falseDest (`(` $falseDestOperands^ `:` type($falseDestOperands) `)`)?
attr-dict
}];
let builders = [
OpBuilder<(ins "Value":$condition, "Block *":$trueDest,
"ValueRange":$trueOperands, "Block *":$falseDest,
"ValueRange":$falseOperands,
CArg<"std::optional<std::pair<uint32_t, uint32_t>>", "{}">:$weights)>,
OpBuilder<(ins "Value":$condition, "Block *":$trueDest,
"Block *":$falseDest, CArg<"ValueRange", "{}">:$falseOperands),
[{
build($_builder, $_state, condition, trueDest, ValueRange(), falseDest,
falseOperands);
}]>,
OpBuilder<(ins "Value":$condition, "ValueRange":$trueOperands, "ValueRange":$falseOperands,
"ElementsAttr":$branchWeights, "Block *":$trueDest, "Block *":$falseDest),
[{
build($_builder, $_state, condition, trueOperands, falseOperands, branchWeights,
{}, trueDest, falseDest);
}]>, LLVM_TerminatorPassthroughOpBuilder];
let hasVerifier = 1;
}
//===----------------------------------------------------------------------===//
// ReturnOp
//===----------------------------------------------------------------------===//
def LLVM_ReturnOp : LLVM_TerminatorOp<"return", [Pure, ReturnLike]> {
let arguments = (ins Optional<LLVM_Type>:$arg);
let assemblyFormat = "attr-dict ($arg^ `:` type($arg))?";
let builders = [
OpBuilder<(ins "ValueRange":$args), [{
build($_builder, $_state, TypeRange(), args);
}]>
];
let hasVerifier = 1;
string llvmInstName = "Ret";
string llvmBuilder = [{
if ($_numOperands != 0)
builder.CreateRet($arg);
else
builder.CreateRetVoid();
}];
string mlirBuilder = [{
FailureOr<SmallVector<Value>> mlirOperands =
moduleImport.convertValues(llvmOperands);
if (failed(mlirOperands))
return failure();
$_op = $_builder.create<LLVM::ReturnOp>($_location, *mlirOperands);
}];
}
def LLVM_ResumeOp : LLVM_TerminatorOp<"resume"> {
let arguments = (ins LLVM_Type:$value);
let assemblyFormat = "$value attr-dict `:` type($value)";
let hasVerifier = 1;
string llvmInstName = "Resume";
string llvmBuilder = [{ builder.CreateResume($value); }];
string mlirBuilder = [{
$_op = $_builder.create<LLVM::ResumeOp>($_location, $value);
}];
}
def LLVM_UnreachableOp : LLVM_TerminatorOp<"unreachable"> {
let assemblyFormat = "attr-dict";
string llvmInstName = "Unreachable";
string llvmBuilder = [{ builder.CreateUnreachable(); }];
string mlirBuilder = [{
$_op = $_builder.create<LLVM::UnreachableOp>($_location);
}];
}
def LLVM_SwitchOp : LLVM_TerminatorOp<"switch",
[AttrSizedOperandSegments, DeclareOpInterfaceMethods<BranchOpInterface>,
Pure]> {
let arguments = (ins
AnyInteger:$value,
Variadic<AnyType>:$defaultOperands,
VariadicOfVariadic<AnyType, "case_operand_segments">:$caseOperands,
OptionalAttr<ElementsAttr>:$case_values,
DenseI32ArrayAttr:$case_operand_segments,
OptionalAttr<ElementsAttr>:$branch_weights
);
let successors = (successor
AnySuccessor:$defaultDestination,
VariadicSuccessor<AnySuccessor>:$caseDestinations
);
let assemblyFormat = [{
$value `:` type($value) `,`
$defaultDestination (`(` $defaultOperands^ `:` type($defaultOperands) `)`)?
`[` `\n` custom<SwitchOpCases>(ref(type($value)), $case_values, $caseDestinations,
$caseOperands, type($caseOperands)) `]`
attr-dict
}];
let hasVerifier = 1;
let builders = [
OpBuilder<(ins "Value":$value,
"Block *":$defaultDestination,
"ValueRange":$defaultOperands,
CArg<"ArrayRef<int32_t>", "{}">:$caseValues,
CArg<"BlockRange", "{}">:$caseDestinations,
CArg<"ArrayRef<ValueRange>", "{}">:$caseOperands,
CArg<"ArrayRef<int32_t>", "{}">:$branchWeights)>,
LLVM_TerminatorPassthroughOpBuilder
];
let extraClassDeclaration = [{
/// Return the operands for the case destination block at the given index.
OperandRange getCaseOperands(unsigned index) {
return getCaseOperands()[index];
}
/// Return a mutable range of operands for the case destination block at the
/// given index.
MutableOperandRange getCaseOperandsMutable(unsigned index) {
return getCaseOperandsMutable()[index];
}
}];
}
////////////////////////////////////////////////////////////////////////////////
// Auxiliary operations (do not appear in LLVM IR but necessary for the dialect
// to work correctly).
////////////////////////////////////////////////////////////////////////////////
def LLVM_AddressOfOp : LLVM_Op<"mlir.addressof",
[Pure, DeclareOpInterfaceMethods<SymbolUserOpInterface>]> {
let arguments = (ins FlatSymbolRefAttr:$global_name);
let results = (outs LLVM_AnyPointer:$res);
let summary = "Creates a pointer pointing to a global or a function";
let description = [{
Creates an SSA value containing a pointer to a global variable or constant
defined by `llvm.mlir.global`. The global value can be defined after its
first referenced. If the global value is a constant, storing into it is not
allowed.
Examples:
```mlir
func @foo() {
// Get the address of a global variable.
%0 = llvm.mlir.addressof @const : !llvm.ptr<i32>
// Use it as a regular pointer.
%1 = llvm.load %0 : !llvm.ptr<i32>
// Get the address of a function.
%2 = llvm.mlir.addressof @foo : !llvm.ptr<func<void ()>>
// The function address can be used for indirect calls.
llvm.call %2() : () -> ()
}
// Define the global.
llvm.mlir.global @const(42 : i32) : i32
```
}];
let builders = [
OpBuilder<(ins "GlobalOp":$global,
CArg<"ArrayRef<NamedAttribute>", "{}">:$attrs),