/
OpenMPDialect.cpp
1428 lines (1243 loc) · 52.7 KB
/
OpenMPDialect.cpp
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
//===- OpenMPDialect.cpp - MLIR Dialect for OpenMP implementation ---------===//
//
// 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 file implements the OpenMP dialect and its operations.
//
//===----------------------------------------------------------------------===//
#include "mlir/Dialect/OpenMP/OpenMPDialect.h"
#include "mlir/Dialect/LLVMIR/LLVMTypes.h"
#include "mlir/IR/Attributes.h"
#include "mlir/IR/DialectImplementation.h"
#include "mlir/IR/OpImplementation.h"
#include "mlir/IR/OperationSupport.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/ADT/TypeSwitch.h"
#include <cstddef>
#include "mlir/Dialect/OpenMP/OpenMPOpsDialect.cpp.inc"
#include "mlir/Dialect/OpenMP/OpenMPOpsEnums.cpp.inc"
#include "mlir/Dialect/OpenMP/OpenMPTypeInterfaces.cpp.inc"
using namespace mlir;
using namespace mlir::omp;
namespace {
/// Model for pointer-like types that already provide a `getElementType` method.
template <typename T>
struct PointerLikeModel
: public PointerLikeType::ExternalModel<PointerLikeModel<T>, T> {
Type getElementType(Type pointer) const {
return pointer.cast<T>().getElementType();
}
};
} // namespace
void OpenMPDialect::initialize() {
addOperations<
#define GET_OP_LIST
#include "mlir/Dialect/OpenMP/OpenMPOps.cpp.inc"
>();
addAttributes<
#define GET_ATTRDEF_LIST
#include "mlir/Dialect/OpenMP/OpenMPOpsAttributes.cpp.inc"
>();
LLVM::LLVMPointerType::attachInterface<
PointerLikeModel<LLVM::LLVMPointerType>>(*getContext());
MemRefType::attachInterface<PointerLikeModel<MemRefType>>(*getContext());
}
//===----------------------------------------------------------------------===//
// ParallelOp
//===----------------------------------------------------------------------===//
void ParallelOp::build(OpBuilder &builder, OperationState &state,
ArrayRef<NamedAttribute> attributes) {
ParallelOp::build(
builder, state, /*if_expr_var=*/nullptr, /*num_threads_var=*/nullptr,
/*allocate_vars=*/ValueRange(), /*allocators_vars=*/ValueRange(),
/*proc_bind_val=*/nullptr);
state.addAttributes(attributes);
}
//===----------------------------------------------------------------------===//
// Parser and printer for Allocate Clause
//===----------------------------------------------------------------------===//
/// Parse an allocate clause with allocators and a list of operands with types.
///
/// allocate ::= `allocate` `(` allocate-operand-list `)`
/// allocate-operand-list :: = allocate-operand |
/// allocator-operand `,` allocate-operand-list
/// allocate-operand :: = ssa-id-and-type -> ssa-id-and-type
/// ssa-id-and-type ::= ssa-id `:` type
static ParseResult parseAllocateAndAllocator(
OpAsmParser &parser,
SmallVectorImpl<OpAsmParser::OperandType> &operandsAllocate,
SmallVectorImpl<Type> &typesAllocate,
SmallVectorImpl<OpAsmParser::OperandType> &operandsAllocator,
SmallVectorImpl<Type> &typesAllocator) {
return parser.parseCommaSeparatedList(
OpAsmParser::Delimiter::Paren, [&]() -> ParseResult {
OpAsmParser::OperandType operand;
Type type;
if (parser.parseOperand(operand) || parser.parseColonType(type))
return failure();
operandsAllocator.push_back(operand);
typesAllocator.push_back(type);
if (parser.parseArrow())
return failure();
if (parser.parseOperand(operand) || parser.parseColonType(type))
return failure();
operandsAllocate.push_back(operand);
typesAllocate.push_back(type);
return success();
});
}
/// Print allocate clause
static void printAllocateAndAllocator(OpAsmPrinter &p,
OperandRange varsAllocate,
OperandRange varsAllocator) {
p << "allocate(";
for (unsigned i = 0; i < varsAllocate.size(); ++i) {
std::string separator = i == varsAllocate.size() - 1 ? ") " : ", ";
p << varsAllocator[i] << " : " << varsAllocator[i].getType() << " -> ";
p << varsAllocate[i] << " : " << varsAllocate[i].getType() << separator;
}
}
LogicalResult ParallelOp::verify() {
if (allocate_vars().size() != allocators_vars().size())
return emitError(
"expected equal sizes for allocate and allocator variables");
return success();
}
void ParallelOp::print(OpAsmPrinter &p) {
p << " ";
if (auto ifCond = if_expr_var())
p << "if(" << ifCond << " : " << ifCond.getType() << ") ";
if (auto threads = num_threads_var())
p << "num_threads(" << threads << " : " << threads.getType() << ") ";
if (!allocate_vars().empty())
printAllocateAndAllocator(p, allocate_vars(), allocators_vars());
if (auto bind = proc_bind_val())
p << "proc_bind(" << stringifyClauseProcBindKind(*bind) << ") ";
p << ' ';
p.printRegion(getRegion());
}
//===----------------------------------------------------------------------===//
// Parser and printer for Linear Clause
//===----------------------------------------------------------------------===//
/// linear ::= `linear` `(` linear-list `)`
/// linear-list := linear-val | linear-val linear-list
/// linear-val := ssa-id-and-type `=` ssa-id-and-type
static ParseResult
parseLinearClause(OpAsmParser &parser,
SmallVectorImpl<OpAsmParser::OperandType> &vars,
SmallVectorImpl<Type> &types,
SmallVectorImpl<OpAsmParser::OperandType> &stepVars) {
if (parser.parseLParen())
return failure();
do {
OpAsmParser::OperandType var;
Type type;
OpAsmParser::OperandType stepVar;
if (parser.parseOperand(var) || parser.parseEqual() ||
parser.parseOperand(stepVar) || parser.parseColonType(type))
return failure();
vars.push_back(var);
types.push_back(type);
stepVars.push_back(stepVar);
} while (succeeded(parser.parseOptionalComma()));
if (parser.parseRParen())
return failure();
return success();
}
/// Print Linear Clause
static void printLinearClause(OpAsmPrinter &p, OperandRange linearVars,
OperandRange linearStepVars) {
size_t linearVarsSize = linearVars.size();
p << "linear(";
for (unsigned i = 0; i < linearVarsSize; ++i) {
std::string separator = i == linearVarsSize - 1 ? ") " : ", ";
p << linearVars[i];
if (linearStepVars.size() > i)
p << " = " << linearStepVars[i];
p << " : " << linearVars[i].getType() << separator;
}
}
//===----------------------------------------------------------------------===//
// Parser and printer for Schedule Clause
//===----------------------------------------------------------------------===//
static ParseResult
verifyScheduleModifiers(OpAsmParser &parser,
SmallVectorImpl<SmallString<12>> &modifiers) {
if (modifiers.size() > 2)
return parser.emitError(parser.getNameLoc()) << " unexpected modifier(s)";
for (const auto &mod : modifiers) {
// Translate the string. If it has no value, then it was not a valid
// modifier!
auto symbol = symbolizeScheduleModifier(mod);
if (!symbol.hasValue())
return parser.emitError(parser.getNameLoc())
<< " unknown modifier type: " << mod;
}
// If we have one modifier that is "simd", then stick a "none" modiifer in
// index 0.
if (modifiers.size() == 1) {
if (symbolizeScheduleModifier(modifiers[0]) == ScheduleModifier::simd) {
modifiers.push_back(modifiers[0]);
modifiers[0] = stringifyScheduleModifier(ScheduleModifier::none);
}
} else if (modifiers.size() == 2) {
// If there are two modifier:
// First modifier should not be simd, second one should be simd
if (symbolizeScheduleModifier(modifiers[0]) == ScheduleModifier::simd ||
symbolizeScheduleModifier(modifiers[1]) != ScheduleModifier::simd)
return parser.emitError(parser.getNameLoc())
<< " incorrect modifier order";
}
return success();
}
/// schedule ::= `schedule` `(` sched-list `)`
/// sched-list ::= sched-val | sched-val sched-list |
/// sched-val `,` sched-modifier
/// sched-val ::= sched-with-chunk | sched-wo-chunk
/// sched-with-chunk ::= sched-with-chunk-types (`=` ssa-id-and-type)?
/// sched-with-chunk-types ::= `static` | `dynamic` | `guided`
/// sched-wo-chunk ::= `auto` | `runtime`
/// sched-modifier ::= sched-mod-val | sched-mod-val `,` sched-mod-val
/// sched-mod-val ::= `monotonic` | `nonmonotonic` | `simd` | `none`
static ParseResult
parseScheduleClause(OpAsmParser &parser, SmallString<8> &schedule,
SmallVectorImpl<SmallString<12>> &modifiers,
Optional<OpAsmParser::OperandType> &chunkSize,
Type &chunkType) {
if (parser.parseLParen())
return failure();
StringRef keyword;
if (parser.parseKeyword(&keyword))
return failure();
schedule = keyword;
if (keyword == "static" || keyword == "dynamic" || keyword == "guided") {
if (succeeded(parser.parseOptionalEqual())) {
chunkSize = OpAsmParser::OperandType{};
if (parser.parseOperand(*chunkSize) || parser.parseColonType(chunkType))
return failure();
} else {
chunkSize = llvm::NoneType::None;
}
} else if (keyword == "auto" || keyword == "runtime") {
chunkSize = llvm::NoneType::None;
} else {
return parser.emitError(parser.getNameLoc()) << " expected schedule kind";
}
// If there is a comma, we have one or more modifiers..
while (succeeded(parser.parseOptionalComma())) {
StringRef mod;
if (parser.parseKeyword(&mod))
return failure();
modifiers.push_back(mod);
}
if (parser.parseRParen())
return failure();
if (verifyScheduleModifiers(parser, modifiers))
return failure();
return success();
}
/// Print schedule clause
static void printScheduleClause(OpAsmPrinter &p, ClauseScheduleKind sched,
Optional<ScheduleModifier> modifier, bool simd,
Value scheduleChunkVar) {
p << "schedule(" << stringifyClauseScheduleKind(sched).lower();
if (scheduleChunkVar)
p << " = " << scheduleChunkVar << " : " << scheduleChunkVar.getType();
if (modifier)
p << ", " << stringifyScheduleModifier(*modifier);
if (simd)
p << ", simd";
p << ") ";
}
//===----------------------------------------------------------------------===//
// Parser, printer and verifier for ReductionVarList
//===----------------------------------------------------------------------===//
/// reduction ::= `reduction` `(` reduction-entry-list `)`
/// reduction-entry-list ::= reduction-entry
/// | reduction-entry-list `,` reduction-entry
/// reduction-entry ::= symbol-ref `->` ssa-id `:` type
static ParseResult
parseReductionVarList(OpAsmParser &parser,
SmallVectorImpl<SymbolRefAttr> &symbols,
SmallVectorImpl<OpAsmParser::OperandType> &operands,
SmallVectorImpl<Type> &types) {
if (failed(parser.parseLParen()))
return failure();
do {
if (parser.parseAttribute(symbols.emplace_back()) || parser.parseArrow() ||
parser.parseOperand(operands.emplace_back()) ||
parser.parseColonType(types.emplace_back()))
return failure();
} while (succeeded(parser.parseOptionalComma()));
return parser.parseRParen();
}
/// Print Reduction clause
static void printReductionVarList(OpAsmPrinter &p,
Optional<ArrayAttr> reductions,
OperandRange reductionVars) {
p << "reduction(";
for (unsigned i = 0, e = reductions->size(); i < e; ++i) {
if (i != 0)
p << ", ";
p << (*reductions)[i] << " -> " << reductionVars[i] << " : "
<< reductionVars[i].getType();
}
p << ") ";
}
/// Verifies Reduction Clause
static LogicalResult verifyReductionVarList(Operation *op,
Optional<ArrayAttr> reductions,
OperandRange reductionVars) {
if (!reductionVars.empty()) {
if (!reductions || reductions->size() != reductionVars.size())
return op->emitOpError()
<< "expected as many reduction symbol references "
"as reduction variables";
} else {
if (reductions)
return op->emitOpError() << "unexpected reduction symbol references";
return success();
}
DenseSet<Value> accumulators;
for (auto args : llvm::zip(reductionVars, *reductions)) {
Value accum = std::get<0>(args);
if (!accumulators.insert(accum).second)
return op->emitOpError() << "accumulator variable used more than once";
Type varType = accum.getType().cast<PointerLikeType>();
auto symbolRef = std::get<1>(args).cast<SymbolRefAttr>();
auto decl =
SymbolTable::lookupNearestSymbolFrom<ReductionDeclareOp>(op, symbolRef);
if (!decl)
return op->emitOpError() << "expected symbol reference " << symbolRef
<< " to point to a reduction declaration";
if (decl.getAccumulatorType() && decl.getAccumulatorType() != varType)
return op->emitOpError()
<< "expected accumulator (" << varType
<< ") to be the same type as reduction declaration ("
<< decl.getAccumulatorType() << ")";
}
return success();
}
//===----------------------------------------------------------------------===//
// Parser, printer and verifier for Synchronization Hint (2.17.12)
//===----------------------------------------------------------------------===//
/// Parses a Synchronization Hint clause. The value of hint is an integer
/// which is a combination of different hints from `omp_sync_hint_t`.
///
/// hint-clause = `hint` `(` hint-value `)`
static ParseResult parseSynchronizationHint(OpAsmParser &parser,
IntegerAttr &hintAttr,
bool parseKeyword = true) {
if (parseKeyword && failed(parser.parseOptionalKeyword("hint"))) {
hintAttr = IntegerAttr::get(parser.getBuilder().getI64Type(), 0);
return success();
}
if (failed(parser.parseLParen()))
return failure();
StringRef hintKeyword;
int64_t hint = 0;
do {
if (failed(parser.parseKeyword(&hintKeyword)))
return failure();
if (hintKeyword == "uncontended")
hint |= 1;
else if (hintKeyword == "contended")
hint |= 2;
else if (hintKeyword == "nonspeculative")
hint |= 4;
else if (hintKeyword == "speculative")
hint |= 8;
else
return parser.emitError(parser.getCurrentLocation())
<< hintKeyword << " is not a valid hint";
} while (succeeded(parser.parseOptionalComma()));
if (failed(parser.parseRParen()))
return failure();
hintAttr = IntegerAttr::get(parser.getBuilder().getI64Type(), hint);
return success();
}
/// Prints a Synchronization Hint clause
static void printSynchronizationHint(OpAsmPrinter &p, Operation *op,
IntegerAttr hintAttr) {
int64_t hint = hintAttr.getInt();
if (hint == 0)
return;
// Helper function to get n-th bit from the right end of `value`
auto bitn = [](int value, int n) -> bool { return value & (1 << n); };
bool uncontended = bitn(hint, 0);
bool contended = bitn(hint, 1);
bool nonspeculative = bitn(hint, 2);
bool speculative = bitn(hint, 3);
SmallVector<StringRef> hints;
if (uncontended)
hints.push_back("uncontended");
if (contended)
hints.push_back("contended");
if (nonspeculative)
hints.push_back("nonspeculative");
if (speculative)
hints.push_back("speculative");
p << "hint(";
llvm::interleaveComma(hints, p);
p << ") ";
}
/// Verifies a synchronization hint clause
static LogicalResult verifySynchronizationHint(Operation *op, uint64_t hint) {
// Helper function to get n-th bit from the right end of `value`
auto bitn = [](int value, int n) -> bool { return value & (1 << n); };
bool uncontended = bitn(hint, 0);
bool contended = bitn(hint, 1);
bool nonspeculative = bitn(hint, 2);
bool speculative = bitn(hint, 3);
if (uncontended && contended)
return op->emitOpError() << "the hints omp_sync_hint_uncontended and "
"omp_sync_hint_contended cannot be combined";
if (nonspeculative && speculative)
return op->emitOpError() << "the hints omp_sync_hint_nonspeculative and "
"omp_sync_hint_speculative cannot be combined.";
return success();
}
enum ClauseType {
ifClause,
numThreadsClause,
deviceClause,
threadLimitClause,
allocateClause,
procBindClause,
reductionClause,
nowaitClause,
linearClause,
scheduleClause,
collapseClause,
orderClause,
orderedClause,
memoryOrderClause,
hintClause,
COUNT
};
//===----------------------------------------------------------------------===//
// Parser for Clause List
//===----------------------------------------------------------------------===//
/// Parse a clause attribute `(` $value `)`.
template <typename ClauseAttr>
static ParseResult parseClauseAttr(AsmParser &parser, OperationState &state,
StringRef attrName, StringRef name) {
using ClauseT = decltype(std::declval<ClauseAttr>().getValue());
StringRef enumStr;
SMLoc loc = parser.getCurrentLocation();
if (parser.parseLParen() || parser.parseKeyword(&enumStr) ||
parser.parseRParen())
return failure();
if (Optional<ClauseT> enumValue = symbolizeEnum<ClauseT>(enumStr)) {
auto attr = ClauseAttr::get(parser.getContext(), *enumValue);
state.addAttribute(attrName, attr);
return success();
}
return parser.emitError(loc, "invalid ") << name << " kind";
}
/// Parse a list of clauses. The clauses can appear in any order, but their
/// operand segment indices are in the same order that they are passed in the
/// `clauses` list. The operand segments are added over the prevSegments
/// clause-list ::= clause clause-list | empty
/// clause ::= if | num-threads | allocate | proc-bind | reduction | nowait
/// | linear | schedule | collapse | order | ordered | inclusive
/// if ::= `if` `(` ssa-id-and-type `)`
/// num-threads ::= `num_threads` `(` ssa-id-and-type `)`
/// allocate ::= `allocate` `(` allocate-operand-list `)`
/// proc-bind ::= `proc_bind` `(` (`master` | `close` | `spread`) `)`
/// reduction ::= `reduction` `(` reduction-entry-list `)`
/// nowait ::= `nowait`
/// linear ::= `linear` `(` linear-list `)`
/// schedule ::= `schedule` `(` sched-list `)`
/// collapse ::= `collapse` `(` ssa-id-and-type `)`
/// order ::= `order` `(` `concurrent` `)`
/// ordered ::= `ordered` `(` ssa-id-and-type `)`
/// inclusive ::= `inclusive`
///
/// Note that each clause can only appear once in the clase-list.
static ParseResult parseClauses(OpAsmParser &parser, OperationState &result,
SmallVectorImpl<ClauseType> &clauses,
SmallVectorImpl<int> &segments) {
// Check done[clause] to see if it has been parsed already
BitVector done(ClauseType::COUNT, false);
// See pos[clause] to get position of clause in operand segments
SmallVector<int> pos(ClauseType::COUNT, -1);
// Stores the last parsed clause keyword
StringRef clauseKeyword;
StringRef opName = result.name.getStringRef();
// Containers for storing operands, types and attributes for various clauses
std::pair<OpAsmParser::OperandType, Type> ifCond;
std::pair<OpAsmParser::OperandType, Type> numThreads;
std::pair<OpAsmParser::OperandType, Type> device;
std::pair<OpAsmParser::OperandType, Type> threadLimit;
SmallVector<OpAsmParser::OperandType> allocates, allocators;
SmallVector<Type> allocateTypes, allocatorTypes;
SmallVector<SymbolRefAttr> reductionSymbols;
SmallVector<OpAsmParser::OperandType> reductionVars;
SmallVector<Type> reductionVarTypes;
SmallVector<OpAsmParser::OperandType> linears;
SmallVector<Type> linearTypes;
SmallVector<OpAsmParser::OperandType> linearSteps;
SmallString<8> schedule;
SmallVector<SmallString<12>> modifiers;
Optional<OpAsmParser::OperandType> scheduleChunkSize;
Type scheduleChunkType;
// Compute the position of clauses in operand segments
int currPos = 0;
for (ClauseType clause : clauses) {
// Skip the following clauses - they do not take any position in operand
// segments
if (clause == procBindClause || clause == nowaitClause ||
clause == collapseClause || clause == orderClause ||
clause == orderedClause)
continue;
pos[clause] = currPos++;
// For the following clauses, two positions are reserved in the operand
// segments
if (clause == allocateClause || clause == linearClause)
currPos++;
}
SmallVector<int> clauseSegments(currPos);
// Helper function to check if a clause is allowed/repeated or not
auto checkAllowed = [&](ClauseType clause) -> ParseResult {
if (!llvm::is_contained(clauses, clause))
return parser.emitError(parser.getCurrentLocation())
<< clauseKeyword << " is not a valid clause for the " << opName
<< " operation";
if (done[clause])
return parser.emitError(parser.getCurrentLocation())
<< "at most one " << clauseKeyword << " clause can appear on the "
<< opName << " operation";
done[clause] = true;
return success();
};
while (succeeded(parser.parseOptionalKeyword(&clauseKeyword))) {
if (clauseKeyword == "if") {
if (checkAllowed(ifClause) || parser.parseLParen() ||
parser.parseOperand(ifCond.first) ||
parser.parseColonType(ifCond.second) || parser.parseRParen())
return failure();
clauseSegments[pos[ifClause]] = 1;
} else if (clauseKeyword == "num_threads") {
if (checkAllowed(numThreadsClause) || parser.parseLParen() ||
parser.parseOperand(numThreads.first) ||
parser.parseColonType(numThreads.second) || parser.parseRParen())
return failure();
clauseSegments[pos[numThreadsClause]] = 1;
} else if (clauseKeyword == "device") {
if (checkAllowed(deviceClause) || parser.parseLParen() ||
parser.parseOperand(device.first) ||
parser.parseColonType(device.second) || parser.parseRParen())
return failure();
clauseSegments[pos[deviceClause]] = 1;
} else if (clauseKeyword == "thread_limit") {
if (checkAllowed(threadLimitClause) || parser.parseLParen() ||
parser.parseOperand(threadLimit.first) ||
parser.parseColonType(threadLimit.second) || parser.parseRParen())
return failure();
clauseSegments[pos[threadLimitClause]] = 1;
} else if (clauseKeyword == "allocate") {
if (checkAllowed(allocateClause) ||
parseAllocateAndAllocator(parser, allocates, allocateTypes,
allocators, allocatorTypes))
return failure();
clauseSegments[pos[allocateClause]] = allocates.size();
clauseSegments[pos[allocateClause] + 1] = allocators.size();
} else if (clauseKeyword == "proc_bind") {
if (checkAllowed(procBindClause) ||
parseClauseAttr<ClauseProcBindKindAttr>(parser, result,
"proc_bind_val", "proc bind"))
return failure();
} else if (clauseKeyword == "reduction") {
if (checkAllowed(reductionClause) ||
parseReductionVarList(parser, reductionSymbols, reductionVars,
reductionVarTypes))
return failure();
clauseSegments[pos[reductionClause]] = reductionVars.size();
} else if (clauseKeyword == "nowait") {
if (checkAllowed(nowaitClause))
return failure();
auto attr = UnitAttr::get(parser.getBuilder().getContext());
result.addAttribute("nowait", attr);
} else if (clauseKeyword == "linear") {
if (checkAllowed(linearClause) ||
parseLinearClause(parser, linears, linearTypes, linearSteps))
return failure();
clauseSegments[pos[linearClause]] = linears.size();
clauseSegments[pos[linearClause] + 1] = linearSteps.size();
} else if (clauseKeyword == "schedule") {
if (checkAllowed(scheduleClause) ||
parseScheduleClause(parser, schedule, modifiers, scheduleChunkSize,
scheduleChunkType))
return failure();
if (scheduleChunkSize) {
clauseSegments[pos[scheduleClause]] = 1;
}
} else if (clauseKeyword == "collapse") {
auto type = parser.getBuilder().getI64Type();
mlir::IntegerAttr attr;
if (checkAllowed(collapseClause) || parser.parseLParen() ||
parser.parseAttribute(attr, type) || parser.parseRParen())
return failure();
result.addAttribute("collapse_val", attr);
} else if (clauseKeyword == "ordered") {
mlir::IntegerAttr attr;
if (checkAllowed(orderedClause))
return failure();
if (succeeded(parser.parseOptionalLParen())) {
auto type = parser.getBuilder().getI64Type();
if (parser.parseAttribute(attr, type) || parser.parseRParen())
return failure();
} else {
// Use 0 to represent no ordered parameter was specified
attr = parser.getBuilder().getI64IntegerAttr(0);
}
result.addAttribute("ordered_val", attr);
} else if (clauseKeyword == "order") {
if (checkAllowed(orderClause) ||
parseClauseAttr<ClauseOrderKindAttr>(parser, result, "order_val",
"order"))
return failure();
} else if (clauseKeyword == "memory_order") {
if (checkAllowed(memoryOrderClause) ||
parseClauseAttr<ClauseMemoryOrderKindAttr>(
parser, result, "memory_order", "memory order"))
return failure();
} else if (clauseKeyword == "hint") {
IntegerAttr hint;
if (checkAllowed(hintClause) ||
parseSynchronizationHint(parser, hint, false))
return failure();
result.addAttribute("hint", hint);
} else {
return parser.emitError(parser.getNameLoc())
<< clauseKeyword << " is not a valid clause";
}
}
// Add if parameter.
if (done[ifClause] && clauseSegments[pos[ifClause]] &&
failed(
parser.resolveOperand(ifCond.first, ifCond.second, result.operands)))
return failure();
// Add num_threads parameter.
if (done[numThreadsClause] && clauseSegments[pos[numThreadsClause]] &&
failed(parser.resolveOperand(numThreads.first, numThreads.second,
result.operands)))
return failure();
// Add device parameter.
if (done[deviceClause] && clauseSegments[pos[deviceClause]] &&
failed(
parser.resolveOperand(device.first, device.second, result.operands)))
return failure();
// Add thread_limit parameter.
if (done[threadLimitClause] && clauseSegments[pos[threadLimitClause]] &&
failed(parser.resolveOperand(threadLimit.first, threadLimit.second,
result.operands)))
return failure();
// Add allocate parameters.
if (done[allocateClause] && clauseSegments[pos[allocateClause]] &&
failed(parser.resolveOperands(allocates, allocateTypes,
allocates[0].location, result.operands)))
return failure();
// Add allocator parameters.
if (done[allocateClause] && clauseSegments[pos[allocateClause] + 1] &&
failed(parser.resolveOperands(allocators, allocatorTypes,
allocators[0].location, result.operands)))
return failure();
// Add reduction parameters and symbols
if (done[reductionClause] && clauseSegments[pos[reductionClause]]) {
if (failed(parser.resolveOperands(reductionVars, reductionVarTypes,
parser.getNameLoc(), result.operands)))
return failure();
SmallVector<Attribute> reductions(reductionSymbols.begin(),
reductionSymbols.end());
result.addAttribute("reductions",
parser.getBuilder().getArrayAttr(reductions));
}
// Add linear parameters
if (done[linearClause] && clauseSegments[pos[linearClause]]) {
auto linearStepType = parser.getBuilder().getI32Type();
SmallVector<Type> linearStepTypes(linearSteps.size(), linearStepType);
if (failed(parser.resolveOperands(linears, linearTypes, linears[0].location,
result.operands)) ||
failed(parser.resolveOperands(linearSteps, linearStepTypes,
linearSteps[0].location,
result.operands)))
return failure();
}
// Add schedule parameters
if (done[scheduleClause] && !schedule.empty()) {
schedule[0] = llvm::toUpper(schedule[0]);
if (Optional<ClauseScheduleKind> sched =
symbolizeClauseScheduleKind(schedule)) {
auto attr = ClauseScheduleKindAttr::get(parser.getContext(), *sched);
result.addAttribute("schedule_val", attr);
} else {
return parser.emitError(parser.getCurrentLocation(),
"invalid schedule kind");
}
if (!modifiers.empty()) {
SMLoc loc = parser.getCurrentLocation();
if (Optional<ScheduleModifier> mod =
symbolizeScheduleModifier(modifiers[0])) {
result.addAttribute(
"schedule_modifier",
ScheduleModifierAttr::get(parser.getContext(), *mod));
} else {
return parser.emitError(loc, "invalid schedule modifier");
}
// Only SIMD attribute is allowed here!
if (modifiers.size() > 1) {
assert(symbolizeScheduleModifier(modifiers[1]) ==
ScheduleModifier::simd);
auto attr = UnitAttr::get(parser.getBuilder().getContext());
result.addAttribute("simd_modifier", attr);
}
}
if (scheduleChunkSize)
parser.resolveOperand(*scheduleChunkSize, scheduleChunkType,
result.operands);
}
segments.insert(segments.end(), clauseSegments.begin(), clauseSegments.end());
return success();
}
/// Parses a parallel operation.
///
/// operation ::= `omp.parallel` clause-list
/// clause-list ::= clause | clause clause-list
/// clause ::= if | num-threads | allocate | proc-bind
///
ParseResult ParallelOp::parse(OpAsmParser &parser, OperationState &result) {
SmallVector<ClauseType> clauses = {ifClause, numThreadsClause, allocateClause,
procBindClause};
SmallVector<int> segments;
if (failed(parseClauses(parser, result, clauses, segments)))
return failure();
result.addAttribute("operand_segment_sizes",
parser.getBuilder().getI32VectorAttr(segments));
Region *body = result.addRegion();
SmallVector<OpAsmParser::OperandType> regionArgs;
SmallVector<Type> regionArgTypes;
if (parser.parseRegion(*body, regionArgs, regionArgTypes))
return failure();
return success();
}
//===----------------------------------------------------------------------===//
// Parser, printer and verifier for SectionsOp
//===----------------------------------------------------------------------===//
/// Parses an OpenMP Sections operation
///
/// sections ::= `omp.sections` clause-list
/// clause-list ::= clause clause-list | empty
/// clause ::= reduction | allocate | nowait
ParseResult SectionsOp::parse(OpAsmParser &parser, OperationState &result) {
SmallVector<ClauseType> clauses = {reductionClause, allocateClause,
nowaitClause};
SmallVector<int> segments;
if (failed(parseClauses(parser, result, clauses, segments)))
return failure();
result.addAttribute("operand_segment_sizes",
parser.getBuilder().getI32VectorAttr(segments));
// Now parse the body.
Region *body = result.addRegion();
if (parser.parseRegion(*body))
return failure();
return success();
}
void SectionsOp::print(OpAsmPrinter &p) {
p << " ";
if (!reduction_vars().empty())
printReductionVarList(p, reductions(), reduction_vars());
if (!allocate_vars().empty())
printAllocateAndAllocator(p, allocate_vars(), allocators_vars());
if (nowait())
p << "nowait";
p << ' ';
p.printRegion(region());
}
LogicalResult SectionsOp::verify() {
if (allocate_vars().size() != allocators_vars().size())
return emitError(
"expected equal sizes for allocate and allocator variables");
for (auto &inst : *region().begin()) {
if (!(isa<SectionOp>(inst) || isa<TerminatorOp>(inst))) {
return emitOpError()
<< "expected omp.section op or terminator op inside region";
}
}
return verifyReductionVarList(*this, reductions(), reduction_vars());
}
/// Parses an OpenMP Workshare Loop operation
///
/// wsloop ::= `omp.wsloop` loop-control clause-list
/// loop-control ::= `(` ssa-id-list `)` `:` type `=` loop-bounds
/// loop-bounds := `(` ssa-id-list `)` to `(` ssa-id-list `)` inclusive? steps
/// steps := `step` `(`ssa-id-list`)`
/// clause-list ::= clause clause-list | empty
/// clause ::= linear | schedule | collapse | nowait | ordered | order
/// | reduction
ParseResult WsLoopOp::parse(OpAsmParser &parser, OperationState &result) {
// Parse an opening `(` followed by induction variables followed by `)`
SmallVector<OpAsmParser::OperandType> ivs;
if (parser.parseRegionArgumentList(ivs, /*requiredOperandCount=*/-1,
OpAsmParser::Delimiter::Paren))
return failure();
int numIVs = static_cast<int>(ivs.size());
Type loopVarType;
if (parser.parseColonType(loopVarType))
return failure();
// Parse loop bounds.
SmallVector<OpAsmParser::OperandType> lower;
if (parser.parseEqual() ||
parser.parseOperandList(lower, numIVs, OpAsmParser::Delimiter::Paren) ||
parser.resolveOperands(lower, loopVarType, result.operands))
return failure();
SmallVector<OpAsmParser::OperandType> upper;
if (parser.parseKeyword("to") ||
parser.parseOperandList(upper, numIVs, OpAsmParser::Delimiter::Paren) ||
parser.resolveOperands(upper, loopVarType, result.operands))
return failure();
if (succeeded(parser.parseOptionalKeyword("inclusive"))) {
auto attr = UnitAttr::get(parser.getBuilder().getContext());
result.addAttribute("inclusive", attr);
}
// Parse step values.
SmallVector<OpAsmParser::OperandType> steps;
if (parser.parseKeyword("step") ||
parser.parseOperandList(steps, numIVs, OpAsmParser::Delimiter::Paren) ||
parser.resolveOperands(steps, loopVarType, result.operands))
return failure();
SmallVector<ClauseType> clauses = {
linearClause, reductionClause, collapseClause, orderClause,
orderedClause, nowaitClause, scheduleClause};
SmallVector<int> segments{numIVs, numIVs, numIVs};
if (failed(parseClauses(parser, result, clauses, segments)))
return failure();
result.addAttribute("operand_segment_sizes",
parser.getBuilder().getI32VectorAttr(segments));
// Now parse the body.
Region *body = result.addRegion();
SmallVector<Type> ivTypes(numIVs, loopVarType);
SmallVector<OpAsmParser::OperandType> blockArgs(ivs);
if (parser.parseRegion(*body, blockArgs, ivTypes))
return failure();
return success();
}
void WsLoopOp::print(OpAsmPrinter &p) {
auto args = getRegion().front().getArguments();
p << " (" << args << ") : " << args[0].getType() << " = (" << lowerBound()
<< ") to (" << upperBound() << ") ";
if (inclusive()) {
p << "inclusive ";
}
p << "step (" << step() << ") ";
if (!linear_vars().empty())
printLinearClause(p, linear_vars(), linear_step_vars());
if (auto sched = schedule_val())
printScheduleClause(p, sched.getValue(), schedule_modifier(),
simd_modifier(), schedule_chunk_var());
if (auto collapse = collapse_val())
p << "collapse(" << collapse << ") ";
if (nowait())
p << "nowait ";
if (auto ordered = ordered_val())
p << "ordered(" << ordered << ") ";
if (auto order = order_val())
p << "order(" << stringifyClauseOrderKind(*order) << ") ";
if (!reduction_vars().empty())
printReductionVarList(p, reductions(), reduction_vars());
p << ' ';
p.printRegion(region(), /*printEntryBlockArgs=*/false);
}
//===----------------------------------------------------------------------===//
// ReductionOp
//===----------------------------------------------------------------------===//
static ParseResult parseAtomicReductionRegion(OpAsmParser &parser,
Region ®ion) {
if (parser.parseOptionalKeyword("atomic"))
return success();
return parser.parseRegion(region);
}