31#include "llvm/ADT/ArrayRef.h"
32#include "llvm/ADT/PostOrderIterator.h"
33#include "llvm/ADT/STLExtras.h"
34#include "llvm/ADT/STLForwardCompat.h"
35#include "llvm/ADT/SmallString.h"
36#include "llvm/ADT/StringRef.h"
37#include "llvm/ADT/TypeSwitch.h"
38#include "llvm/ADT/bit.h"
39#include "llvm/Support/InterleavedRange.h"
45#include "mlir/Dialect/OpenMP/OpenMPOpsDialect.cpp.inc"
46#include "mlir/Dialect/OpenMP/OpenMPOpsEnums.cpp.inc"
47#include "mlir/Dialect/OpenMP/OpenMPOpsInterfaces.cpp.inc"
48#include "mlir/Dialect/OpenMP/OpenMPTypeInterfaces.cpp.inc"
56 return attrs.empty() ?
nullptr : ArrayAttr::get(context, attrs);
70struct MemRefPointerLikeModel
71 :
public PointerLikeType::ExternalModel<MemRefPointerLikeModel,
74 return llvm::cast<MemRefType>(pointer).getElementType();
78struct LLVMPointerPointerLikeModel
79 :
public PointerLikeType::ExternalModel<LLVMPointerPointerLikeModel,
80 LLVM::LLVMPointerType> {
100 CanonicalLoopOp op) {
105 bool isRegionArgOfOp;
115 assert(isRegionArgOfOp &&
"Must describe a region operand");
118 size_t &getArgIdx() {
119 assert(isRegionArgOfOp &&
"Must describe a region operand");
124 assert(!isRegionArgOfOp &&
"Must describe a operation of a region");
128 assert(!isRegionArgOfOp &&
"Must describe a operation of a region");
131 bool isLoopOp()
const {
132 assert(!isRegionArgOfOp &&
"Must describe a operation of a region");
133 return isa<CanonicalLoopOp>(op);
135 Region *&getParentRegion() {
136 assert(!isRegionArgOfOp &&
"Must describe a operation of a region");
139 size_t &getLoopDepth() {
140 assert(!isRegionArgOfOp &&
"Must describe a operation of a region");
144 void skipIf(
bool v =
true) { skip = skip || v; }
162 llvm::ReversePostOrderTraversal<Block *> traversal(&r->
getBlocks().front());
165 size_t sequentialIdx = -1;
166 bool isOnlyContainerOp =
true;
167 for (
Block *
b : traversal) {
169 if (&op == o && !found) {
173 if (op.getNumRegions()) {
176 isOnlyContainerOp =
false;
178 if (found && !isOnlyContainerOp)
183 Component &containerOpInRegion = components.emplace_back();
184 containerOpInRegion.isRegionArgOfOp =
false;
185 containerOpInRegion.isUnique = isOnlyContainerOp;
186 containerOpInRegion.getContainerOp() = o;
187 containerOpInRegion.getOpPos() = sequentialIdx;
188 containerOpInRegion.getParentRegion() = r;
193 Component ®ionArgOfOperation = components.emplace_back();
194 regionArgOfOperation.isRegionArgOfOp =
true;
195 regionArgOfOperation.isUnique =
true;
196 regionArgOfOperation.getArgIdx() = 0;
197 regionArgOfOperation.getOwnerOp() = parent;
209 for (
auto [idx, region] : llvm::enumerate(o->
getRegions())) {
213 llvm_unreachable(
"Region not child of its parent operation");
215 regionArgOfOperation.isUnique =
false;
216 regionArgOfOperation.getArgIdx() = getRegionIndex(parent, r);
224 for (Component &c : components)
225 c.skipIf(c.isRegionArgOfOp && c.isUnique);
228 size_t numSurroundingLoops = 0;
229 for (Component &c : llvm::reverse(components)) {
234 if (c.isRegionArgOfOp) {
235 numSurroundingLoops = 0;
242 numSurroundingLoops = 0;
244 c.getLoopDepth() = numSurroundingLoops;
247 if (isa<CanonicalLoopOp>(c.getContainerOp()))
248 numSurroundingLoops += 1;
253 bool isLoopNest =
false;
254 for (Component &c : components) {
255 if (c.skip || c.isRegionArgOfOp)
258 if (!isLoopNest && c.getLoopDepth() >= 1) {
261 }
else if (isLoopNest) {
263 c.skipIf(c.isUnique);
267 if (c.getLoopDepth() == 0)
274 for (Component &c : components)
275 c.skipIf(!c.isRegionArgOfOp && c.isUnique &&
276 !isa<CanonicalLoopOp>(c.getContainerOp()));
280 bool newRegion =
true;
281 for (Component &c : llvm::reverse(components)) {
282 c.skipIf(newRegion && c.isUnique);
289 if (!c.isRegionArgOfOp && c.getContainerOp())
295 llvm::raw_svector_ostream NameOS(Name);
296 for (
auto &c : llvm::reverse(components)) {
300 if (c.isRegionArgOfOp)
301 NameOS <<
"_r" << c.getArgIdx();
302 else if (c.getLoopDepth() >= 1)
303 NameOS <<
"_d" << c.getLoopDepth();
305 NameOS <<
"_s" << c.getOpPos();
308 return NameOS.str().str();
311void OpenMPDialect::initialize() {
312 declarePromisedInterface<ConvertToLLVMPatternInterface, OpenMPDialect>();
314 MemRefType::attachInterface<MemRefPointerLikeModel>(*
getContext());
315 LLVM::LLVMPointerType::attachInterface<LLVMPointerPointerLikeModel>(
320 mlir::ModuleOp::attachInterface<mlir::omp::OffloadModuleDefaultModel>(
326 mlir::LLVM::GlobalOp::attachInterface<
329 mlir::LLVM::LLVMFuncOp::attachInterface<
332 mlir::func::FuncOp::attachInterface<
341 if (!isa<DeclareTargetInterface>(op))
342 return op->
emitError() <<
"omp.declare_target can only be applied to "
343 "DeclareTargetInterface ops";
345 auto declareTargetAttr = dyn_cast<DeclareTargetAttr>(attr);
346 if (!declareTargetAttr)
348 <<
"omp.declare_target must be an #omp.declaretarget attribute";
350 if (isa<mlir::FunctionOpInterface>(op)) {
351 if (declareTargetAttr.getAutomap())
353 <<
"omp.declare_target 'automap' is not valid on functions";
356 if (declareTargetAttr.getCaptureClause() ==
357 mlir::omp::DeclareTargetCaptureClause::link)
359 <<
"omp.declare_target 'link' is not valid on functions";
362 if (declareTargetAttr.getImplicit())
364 <<
"omp.declare_target 'implicit' is only valid on functions";
370OpenMPDialect::verifyOperationAttribute(
Operation *op,
372 if (attribute.
getName() ==
"omp.declare_target")
400 allocatorVars.push_back(operand);
401 allocatorTypes.push_back(type);
407 allocateVars.push_back(operand);
408 allocateTypes.push_back(type);
419 for (
unsigned i = 0; i < allocateVars.size(); ++i) {
420 std::string separator = i == allocateVars.size() - 1 ?
"" :
", ";
421 p << allocatorVars[i] <<
" : " << allocatorTypes[i] <<
" -> ";
422 p << allocateVars[i] <<
" : " << allocateTypes[i] << separator;
430template <
typename ClauseAttr>
432 using ClauseT =
decltype(std::declval<ClauseAttr>().getValue());
437 if (std::optional<ClauseT> enumValue = symbolizeEnum<ClauseT>(enumStr)) {
438 attr = ClauseAttr::get(parser.
getContext(), *enumValue);
441 return parser.
emitError(loc,
"invalid clause value: '") << enumStr <<
"'";
444template <
typename ClauseAttr>
446 p << stringifyEnum(attr.getValue());
472 std::optional<omp::LinearModifier> linearModifier;
474 linearModifier = omp::LinearModifier::val;
476 linearModifier = omp::LinearModifier::ref;
478 linearModifier = omp::LinearModifier::uval;
481 bool hasLinearModifierParens = linearModifier.has_value();
482 if (hasLinearModifierParens && parser.
parseLParen())
490 if (hasLinearModifierParens && parser.
parseRParen())
493 linearVars.push_back(var);
494 linearTypes.push_back(type);
495 linearStepVars.push_back(stepVar);
496 linearStepTypes.push_back(stepType);
497 if (linearModifier) {
499 omp::LinearModifierAttr::get(parser.
getContext(), *linearModifier));
501 modifiers.push_back(UnitAttr::get(parser.
getContext()));
507 linearModifiers = ArrayAttr::get(parser.
getContext(), modifiers);
517 size_t linearVarsSize = linearVars.size();
518 for (
unsigned i = 0; i < linearVarsSize; ++i) {
522 Attribute modAttr = linearModifiers ? linearModifiers[i] :
nullptr;
523 auto mod = modAttr ? dyn_cast<omp::LinearModifierAttr>(modAttr) :
nullptr;
525 p << omp::stringifyLinearModifier(mod.getValue()) <<
"(";
527 p << linearVars[i] <<
" : " << linearTypes[i];
528 p <<
" = " << linearStepVars[i] <<
" : " << stepVarTypes[i];
544 if (!linearModifiers)
546 if (linearModifiers->size() != linearVars.size())
548 <<
"expected as many linear modifiers as linear variables";
549 if (!isDeclareSimd) {
550 for (
Attribute attr : *linearModifiers) {
553 auto modAttr = dyn_cast<omp::LinearModifierAttr>(attr);
556 omp::LinearModifier mod = modAttr.getValue();
557 if (mod == omp::LinearModifier::ref || mod == omp::LinearModifier::uval)
559 <<
"linear modifier '" << omp::stringifyLinearModifier(mod)
560 <<
"' may only be specified on a declare simd directive";
575 for (
const auto &it : nontemporalVars)
576 if (!nontemporalItems.insert(it).second)
577 return op->
emitOpError() <<
"nontemporal variable used more than once";
586 std::optional<ArrayAttr> alignments,
589 if (!alignedVars.empty()) {
590 if (!alignments || alignments->size() != alignedVars.size())
592 <<
"expected as many alignment values as aligned variables";
595 return op->
emitOpError() <<
"unexpected alignment values attribute";
601 for (
auto it : alignedVars)
602 if (!alignedItems.insert(it).second)
603 return op->
emitOpError() <<
"aligned variable used more than once";
609 for (
unsigned i = 0; i < (*alignments).size(); ++i) {
610 if (
auto intAttr = llvm::dyn_cast<IntegerAttr>((*alignments)[i])) {
611 if (intAttr.getValue().sle(0))
612 return op->
emitOpError() <<
"alignment should be greater than 0";
614 return op->
emitOpError() <<
"expected integer alignment";
631 if (parser.parseOperand(alignedVars.emplace_back()) ||
632 parser.parseColonType(alignedTypes.emplace_back()) ||
633 parser.parseArrow() ||
634 parser.parseAttribute(alignmentVec.emplace_back())) {
641 alignmentsAttr = ArrayAttr::get(parser.getContext(), alignments);
648 std::optional<ArrayAttr> alignments) {
649 for (
unsigned i = 0; i < alignedVars.size(); ++i) {
652 p << alignedVars[i] <<
" : " << alignedVars[i].
getType();
653 p <<
" -> " << (*alignments)[i];
661 ArrayAttr privateSyms =
nullptr,
bool requirePrivateIndices =
false) {
662 if (allocateVars.size() != allocatorVars.size())
664 "expected equal sizes for allocate and allocator variables");
666 if (allocateVars.empty()) {
667 if (allocateAlignments)
669 "unexpected allocate alignments without allocate variables");
670 if (allocatePrivateIndices)
672 "unexpected allocate private indices without allocate variables");
676 if (allocateAlignments) {
678 if (alignments.size() != allocateVars.size())
680 "expected as many allocate alignments as allocate variables");
681 for (
int64_t alignment : alignments) {
683 return op->
emitError(
"expected non-negative allocate alignments");
684 if (alignment != 0 && (alignment & (alignment - 1)) != 0)
686 "expected positive allocate alignments to be powers of two");
690 if (!allocatePrivateIndices) {
691 if (requirePrivateIndices)
693 "expected an allocate private index for each allocate variable");
698 if (
indices.size() != allocateVars.size())
700 "expected as many allocate private indices as allocate variables");
703 for (
auto [allocateVar, privateIndex] :
704 llvm::zip_equal(allocateVars,
indices)) {
705 if (privateIndex < 0 ||
706 static_cast<uint64_t
>(privateIndex) >= privateVars.size())
707 return op->
emitError(
"allocate private index is out of range");
708 if (!usedPrivateSlots.insert(privateIndex).second)
710 "allocate private index refers to a private variable more than once");
712 Value privateVar = privateVars[privateIndex];
713 if (allocateVar.getType() != privateVar.
getType())
715 <<
"type mismatch between allocate variable and private variable "
718 if (allocateVar != privateVar)
720 <<
"allocate variable does not match private variable at index "
724 static_cast<uint64_t
>(privateIndex) >= privateSyms.size())
726 "allocate private index does not have a privatizer symbol");
728 auto privateSym = dyn_cast<SymbolRefAttr>(privateSyms[privateIndex]);
731 "allocate private index does not reference a privatizer symbol");
732 PrivateClauseOp privatizer =
735 return op->
emitError() <<
"failed to lookup privatizer op with symbol: '"
736 << privateSym <<
"'";
737 if (privatizer.getDataSharingType() != DataSharingClauseType::Private &&
738 privatizer.getDataSharingType() != DataSharingClauseType::FirstPrivate)
740 "allocate private index must refer to private or firstprivate "
754 if (modifiers.size() > 2)
756 for (
const auto &mod : modifiers) {
759 auto symbol = symbolizeScheduleModifier(mod);
762 <<
" unknown modifier type: " << mod;
767 if (modifiers.size() == 1) {
768 if (symbolizeScheduleModifier(modifiers[0]) == ScheduleModifier::simd) {
769 modifiers.push_back(modifiers[0]);
770 modifiers[0] = stringifyScheduleModifier(ScheduleModifier::none);
772 }
else if (modifiers.size() == 2) {
775 if (symbolizeScheduleModifier(modifiers[0]) == ScheduleModifier::simd ||
776 symbolizeScheduleModifier(modifiers[1]) != ScheduleModifier::simd)
778 <<
" incorrect modifier order";
794 ScheduleModifierAttr &scheduleMod, UnitAttr &scheduleSimd,
795 std::optional<OpAsmParser::UnresolvedOperand> &chunkSize,
800 std::optional<mlir::omp::ClauseScheduleKind> schedule =
801 symbolizeClauseScheduleKind(keyword);
805 scheduleAttr = ClauseScheduleKindAttr::get(parser.
getContext(), *schedule);
807 case ClauseScheduleKind::Static:
808 case ClauseScheduleKind::Dynamic:
809 case ClauseScheduleKind::Guided:
815 chunkSize = std::nullopt;
818 case ClauseScheduleKind::Auto:
819 case ClauseScheduleKind::Runtime:
820 case ClauseScheduleKind::Distribute:
821 chunkSize = std::nullopt;
830 modifiers.push_back(mod);
836 if (!modifiers.empty()) {
838 if (std::optional<ScheduleModifier> mod =
839 symbolizeScheduleModifier(modifiers[0])) {
840 scheduleMod = ScheduleModifierAttr::get(parser.
getContext(), *mod);
842 return parser.
emitError(loc,
"invalid schedule modifier");
845 if (modifiers.size() > 1) {
846 assert(symbolizeScheduleModifier(modifiers[1]) == ScheduleModifier::simd);
856 ClauseScheduleKindAttr scheduleKind,
857 ScheduleModifierAttr scheduleMod,
858 UnitAttr scheduleSimd,
Value scheduleChunk,
859 Type scheduleChunkType) {
860 p << stringifyClauseScheduleKind(scheduleKind.getValue());
862 p <<
" = " << scheduleChunk <<
" : " << scheduleChunk.
getType();
864 p <<
", " << stringifyScheduleModifier(scheduleMod.getValue());
876 ClauseOrderKindAttr &order,
877 OrderModifierAttr &orderMod) {
882 if (std::optional<OrderModifier> enumValue =
883 symbolizeOrderModifier(enumStr)) {
884 orderMod = OrderModifierAttr::get(parser.
getContext(), *enumValue);
891 if (std::optional<ClauseOrderKind> enumValue =
892 symbolizeClauseOrderKind(enumStr)) {
893 order = ClauseOrderKindAttr::get(parser.
getContext(), *enumValue);
896 return parser.
emitError(loc,
"invalid clause value: '") << enumStr <<
"'";
900 ClauseOrderKindAttr order,
901 OrderModifierAttr orderMod) {
903 p << stringifyOrderModifier(orderMod.getValue()) <<
":";
905 p << stringifyClauseOrderKind(order.getValue());
908template <
typename ClauseTypeAttr,
typename ClauseType>
911 std::optional<OpAsmParser::UnresolvedOperand> &operand,
913 std::optional<ClauseType> (*symbolizeClause)(StringRef),
914 StringRef clauseName) {
917 if (std::optional<ClauseType> enumValue = symbolizeClause(enumStr)) {
918 prescriptiveness = ClauseTypeAttr::get(parser.
getContext(), *enumValue);
923 <<
"invalid " << clauseName <<
" modifier : '" << enumStr <<
"'";
933 <<
"expected " << clauseName <<
" operand";
936 if (operand.has_value()) {
944template <
typename ClauseTypeAttr,
typename ClauseType>
947 ClauseTypeAttr prescriptiveness,
Value operand,
949 StringRef (*stringifyClauseType)(ClauseType)) {
951 if (prescriptiveness)
952 p << stringifyClauseType(prescriptiveness.getValue()) <<
", ";
955 p << operand <<
": " << operandType;
965 std::optional<OpAsmParser::UnresolvedOperand> &grainsize,
966 Type &grainsizeType) {
968 parser, grainsizeMod, grainsize, grainsizeType,
969 &symbolizeClauseGrainsizeType,
"grainsize");
973 ClauseGrainsizeTypeAttr grainsizeMod,
976 p, op, grainsizeMod, grainsize, grainsizeType,
977 &stringifyClauseGrainsizeType);
987 std::optional<OpAsmParser::UnresolvedOperand> &numTasks,
988 Type &numTasksType) {
990 parser, numTasksMod, numTasks, numTasksType, &symbolizeClauseNumTasksType,
995 ClauseNumTasksTypeAttr numTasksMod,
998 p, op, numTasksMod, numTasks, numTasksType, &stringifyClauseNumTasksType);
1014 return mlir::failure();
1015 inTypeAttr = TypeAttr::get(inType);
1044 if (!typeparams.empty()) {
1045 p <<
'(' << typeparams <<
" : " << typeparamsTypes <<
')';
1047 for (
auto sh :
shape) {
1059 FallbackModifierAttr fallback,
1060 Value dynGroupprivateSize) {
1061 if (!dynGroupprivateSize && (accessGroup || fallback))
1062 return op->
emitOpError(
"dyn_groupprivate modifiers require a size operand");
1068 OpAsmParser &parser, AccessGroupModifierAttr &accessGroupAttr,
1069 FallbackModifierAttr &fallbackAttr,
1070 std::optional<OpAsmParser::UnresolvedOperand> &dynGroupprivateSize,
1073 bool parsedAccessGroup =
false;
1074 bool parsedFallback =
false;
1075 bool parsedSize =
false;
1080 if (parsedAccessGroup)
1082 "duplicate access group modifier");
1083 accessGroupAttr = AccessGroupModifierAttr::get(
1084 parser.
getContext(), AccessGroupModifier::cgroup);
1085 parsedAccessGroup =
true;
1092 "duplicate fallback modifier");
1095 "expected '(' after 'fallback'");
1096 llvm::StringRef fbKind;
1100 "expected fallback modifier (abort/null/default_mem)");
1101 std::optional<FallbackModifier> fbEnum;
1102 if (fbKind ==
"abort")
1103 fbEnum = FallbackModifier::abort;
1104 else if (fbKind ==
"null")
1105 fbEnum = FallbackModifier::null;
1106 else if (fbKind ==
"default_mem")
1107 fbEnum = FallbackModifier::default_mem;
1110 "invalid fallback modifier '" + fbKind +
"'");
1111 fallbackAttr = FallbackModifierAttr::get(parser.
getContext(), *fbEnum);
1114 "expected ')' after fallback modifier");
1115 parsedFallback =
true;
1123 "duplicate size operand");
1124 dynGroupprivateSize = operand;
1128 "expected ':' and type after size operand");
1132 "expected dyn_groupprivate_size operand");
1137 AccessGroupModifierAttr modifierFirst,
1138 FallbackModifierAttr modifierSecond,
1139 Value dynGroupprivateSize,
1142 bool needsComma =
false;
1144 if (modifierFirst) {
1145 printer << modifierFirst.getValue();
1149 if (modifierSecond) {
1152 printer <<
"fallback(";
1153 printer << modifierSecond.getValue();
1158 if (dynGroupprivateSize) {
1161 printer << dynGroupprivateSize <<
" : " << sizeType;
1181 isByRefVec.push_back(parser.parseOptionalKeyword(
"byref").succeeded());
1182 if (parser.parseAttribute(symbolVec.emplace_back()) ||
1183 parser.parseOperand(inReductionVars.emplace_back()))
1193 [&]() { return parser.parseType(inReductionTypes.emplace_back()); }))
1196 if (inReductionVars.size() != inReductionTypes.size())
1201 inReductionSyms = ArrayAttr::get(parser.
getContext(), symbolAttrs);
1218 syms = ArrayAttr::get(ctx, values);
1227 llvm::interleaveComma(
1228 llvm::zip_equal(inReductionVars, syms.getValue(), byref.
asArrayRef()), p,
1230 auto [var, sym, isByRef] = t;
1238 llvm::interleaveComma(inReductionTypes, p);
1246struct MapParseArgs {
1247 SmallVectorImpl<OpAsmParser::UnresolvedOperand> &vars;
1248 SmallVectorImpl<Type> &types;
1249 MapParseArgs(SmallVectorImpl<OpAsmParser::UnresolvedOperand> &vars,
1250 SmallVectorImpl<Type> &types)
1251 : vars(vars), types(types) {}
1253struct PrivateParseArgs {
1254 llvm::SmallVectorImpl<OpAsmParser::UnresolvedOperand> &vars;
1255 llvm::SmallVectorImpl<Type> &types;
1257 UnitAttr &needsBarrier;
1259 PrivateParseArgs(SmallVectorImpl<OpAsmParser::UnresolvedOperand> &vars,
1260 SmallVectorImpl<Type> &types,
ArrayAttr &syms,
1261 UnitAttr &needsBarrier,
1263 : vars(vars), types(types), syms(syms), needsBarrier(needsBarrier),
1264 mapIndices(mapIndices) {}
1267struct LinearParseArgs {
1268 SmallVectorImpl<OpAsmParser::UnresolvedOperand> &vars;
1269 SmallVectorImpl<Type> &types;
1270 SmallVectorImpl<OpAsmParser::UnresolvedOperand> &stepVars;
1271 SmallVectorImpl<Type> &stepTypes;
1275 LinearParseArgs(SmallVectorImpl<OpAsmParser::UnresolvedOperand> &vars,
1276 SmallVectorImpl<Type> &types,
1277 SmallVectorImpl<OpAsmParser::UnresolvedOperand> &stepVars,
1278 SmallVectorImpl<Type> &stepTypes,
ArrayAttr &varTypes,
1280 : vars(vars), types(types), stepVars(stepVars), stepTypes(stepTypes),
1281 varTypes(varTypes), modifiers(modifiers), syms(syms) {}
1284struct ReductionParseArgs {
1285 SmallVectorImpl<OpAsmParser::UnresolvedOperand> &vars;
1286 SmallVectorImpl<Type> &types;
1290 ReductionParseArgs(SmallVectorImpl<OpAsmParser::UnresolvedOperand> &vars,
1293 : vars(vars), types(types), byref(byref), syms(syms), modifier(mod) {}
1296struct AllRegionParseArgs {
1297 std::optional<MapParseArgs> hasDeviceAddrArgs;
1298 std::optional<MapParseArgs> hostEvalArgs;
1299 std::optional<ReductionParseArgs> inReductionArgs;
1300 std::optional<LinearParseArgs> linearArgs;
1301 std::optional<MapParseArgs> mapArgs;
1302 std::optional<PrivateParseArgs> privateArgs;
1303 std::optional<ReductionParseArgs> reductionArgs;
1304 std::optional<ReductionParseArgs> taskReductionArgs;
1305 std::optional<MapParseArgs> useDeviceAddrArgs;
1306 std::optional<MapParseArgs> useDevicePtrArgs;
1311 return "private_barrier";
1321 UnitAttr *needsBarrier =
nullptr) {
1325 unsigned regionArgOffset = regionPrivateArgs.size();
1333 ReductionModifier mod = ReductionModifier::defaultmod;
1334 if (succeeded(parser.parseOptionalKeyword(
"task")))
1335 mod = ReductionModifier::task;
1336 else if (succeeded(parser.parseOptionalKeyword(
"inscan")))
1337 mod = ReductionModifier::inscan;
1338 else if (succeeded(parser.parseOptionalKeyword(
"defaultmod")))
1339 mod = ReductionModifier::defaultmod;
1340 modifiers.push_back(
1341 ReductionModifierAttr::get(parser.getContext(), mod));
1344 isByRefVec.push_back(
1362 mapIndicesVec.push_back(-1);
1371 return parser.parseType(types.emplace_back());
1375 if (llvm::any_of(modifiers, [](
Attribute attr) {
1376 return cast<ReductionModifierAttr>(attr).getValue() !=
1377 ReductionModifier::defaultmod;
1379 *modifier = ArrayAttr::get(parser.
getContext(), modifiers);
1381 if (operands.size() != types.size())
1390 *needsBarrier = mlir::UnitAttr::get(parser.
getContext());
1393 auto *argsBegin = regionPrivateArgs.begin();
1395 argsBegin + regionArgOffset + types.size());
1396 for (
auto [prv, type] : llvm::zip_equal(argsSubrange, types)) {
1402 *symbols = ArrayAttr::get(parser.
getContext(), symbolAttrs);
1405 if (!mapIndicesVec.empty())
1418 StringRef keyword, std::optional<MapParseArgs> mapArgs) {
1433 StringRef keyword, std::optional<PrivateParseArgs> privateArgs) {
1439 parser, privateArgs->vars, privateArgs->types, entryBlockArgs,
1440 &privateArgs->syms, privateArgs->mapIndices,
nullptr,
1441 nullptr, &privateArgs->needsBarrier)))
1450 StringRef keyword, std::optional<ReductionParseArgs> reductionArgs) {
1455 parser, reductionArgs->vars, reductionArgs->types, entryBlockArgs,
1456 &reductionArgs->syms,
nullptr, &reductionArgs->byref,
1457 reductionArgs->modifier)))
1468 StringRef keyword, std::optional<LinearParseArgs> linearArgs) {
1476 std::optional<LinearModifier> modifier;
1477 if (succeeded(parser.parseOptionalKeyword(
"val")))
1478 modifier = LinearModifier::val;
1479 else if (succeeded(parser.parseOptionalKeyword(
"ref")))
1480 modifier = LinearModifier::ref;
1481 else if (succeeded(parser.parseOptionalKeyword(
"uval")))
1482 modifier = LinearModifier::uval;
1483 if (modifier && parser.parseLParen())
1487 OpAsmParser::Argument &arg = entryBlockArgs.emplace_back();
1488 if (parser.parseAttribute(sym) ||
1489 parser.parseOperand(linearArgs->vars.emplace_back()) ||
1490 parser.parseArrow() || parser.parseArgument(arg) ||
1491 parser.parseColonType(linearArgs->types.emplace_back()) ||
1492 parser.parseEqual() ||
1493 parser.parseOperand(linearArgs->stepVars.emplace_back()) ||
1494 parser.parseColonType(linearArgs->stepTypes.emplace_back()))
1496 arg.type = linearArgs->types.back();
1498 if (modifier && parser.parseRParen())
1501 syms.push_back(sym);
1502 modifiers.push_back(
1503 modifier ? Attribute(LinearModifierAttr::get(ctx, *modifier))
1504 : Attribute(UnitAttr::get(ctx)));
1510 linearArgs->syms = ArrayAttr::get(ctx, syms);
1511 linearArgs->modifiers = ArrayAttr::get(ctx, modifiers);
1521 AllRegionParseArgs args) {
1525 args.hasDeviceAddrArgs)))
1527 <<
"invalid `has_device_addr` format";
1530 args.hostEvalArgs)))
1532 <<
"invalid `host_eval` format";
1535 args.inReductionArgs)))
1537 <<
"invalid `in_reduction` format";
1542 <<
"invalid `linear` format";
1547 <<
"invalid `map_entries` format";
1552 <<
"invalid `private` format";
1555 args.reductionArgs)))
1557 <<
"invalid `reduction` format";
1560 args.taskReductionArgs)))
1562 <<
"invalid `task_reduction` format";
1565 args.useDeviceAddrArgs)))
1567 <<
"invalid `use_device_addr` format";
1570 args.useDevicePtrArgs)))
1572 <<
"invalid `use_device_addr` format";
1574 return parser.
parseRegion(region, entryBlockArgs);
1590 AllRegionParseArgs args;
1591 args.hasDeviceAddrArgs.emplace(hasDeviceAddrVars, hasDeviceAddrTypes);
1592 args.hostEvalArgs.emplace(hostEvalVars, hostEvalTypes);
1593 args.mapArgs.emplace(mapVars, mapTypes);
1594 args.privateArgs.emplace(privateVars, privateTypes, privateSyms,
1595 privateNeedsBarrier, &privateMaps);
1606 UnitAttr &privateNeedsBarrier) {
1607 AllRegionParseArgs args;
1608 args.inReductionArgs.emplace(inReductionVars, inReductionTypes,
1609 inReductionByref, inReductionSyms);
1610 args.privateArgs.emplace(privateVars, privateTypes, privateSyms,
1611 privateNeedsBarrier);
1622 UnitAttr &privateNeedsBarrier,
ArrayAttr &reductionMods,
1626 AllRegionParseArgs args;
1627 args.inReductionArgs.emplace(inReductionVars, inReductionTypes,
1628 inReductionByref, inReductionSyms);
1629 args.privateArgs.emplace(privateVars, privateTypes, privateSyms,
1630 privateNeedsBarrier);
1631 args.reductionArgs.emplace(reductionVars, reductionTypes, reductionByref,
1632 reductionSyms, &reductionMods);
1640 UnitAttr &privateNeedsBarrier) {
1641 AllRegionParseArgs args;
1642 args.privateArgs.emplace(privateVars, privateTypes, privateSyms,
1643 privateNeedsBarrier);
1651 UnitAttr &privateNeedsBarrier,
ArrayAttr &reductionMods,
1655 AllRegionParseArgs args;
1656 args.privateArgs.emplace(privateVars, privateTypes, privateSyms,
1657 privateNeedsBarrier);
1658 args.reductionArgs.emplace(reductionVars, reductionTypes, reductionByref,
1659 reductionSyms, &reductionMods);
1672 UnitAttr &privateNeedsBarrier,
ArrayAttr &reductionMods,
1676 AllRegionParseArgs args;
1677 args.linearArgs.emplace(linearVars, linearTypes, linearStepVars,
1678 linearStepTypes, linearVarTypes, linearModifiers,
1680 args.privateArgs.emplace(privateVars, privateTypes, privateSyms,
1681 privateNeedsBarrier);
1682 args.reductionArgs.emplace(reductionVars, reductionTypes, reductionByref,
1683 reductionSyms, &reductionMods);
1692 AllRegionParseArgs args;
1693 args.taskReductionArgs.emplace(taskReductionVars, taskReductionTypes,
1694 taskReductionByref, taskReductionSyms);
1704 AllRegionParseArgs args;
1705 args.useDeviceAddrArgs.emplace(useDeviceAddrVars, useDeviceAddrTypes);
1706 args.useDevicePtrArgs.emplace(useDevicePtrVars, useDevicePtrTypes);
1715struct MapPrintArgs {
1720struct PrivatePrintArgs {
1724 UnitAttr needsBarrier;
1728 : vars(vars), types(types), syms(syms), needsBarrier(needsBarrier),
1729 mapIndices(mapIndices) {}
1731struct LinearPrintArgs {
1742 : vars(vars), types(types), stepVars(stepVars), stepTypes(stepTypes),
1743 varTypes(varTypes), modifiers(modifiers), syms(syms) {}
1745struct ReductionPrintArgs {
1753 : vars(vars), types(types), byref(byref), syms(syms), modifier(mod) {}
1755struct AllRegionPrintArgs {
1756 std::optional<MapPrintArgs> hasDeviceAddrArgs;
1757 std::optional<MapPrintArgs> hostEvalArgs;
1758 std::optional<ReductionPrintArgs> inReductionArgs;
1759 std::optional<LinearPrintArgs> linearArgs;
1760 std::optional<MapPrintArgs> mapArgs;
1761 std::optional<PrivatePrintArgs> privateArgs;
1762 std::optional<ReductionPrintArgs> reductionArgs;
1763 std::optional<ReductionPrintArgs> taskReductionArgs;
1764 std::optional<MapPrintArgs> useDeviceAddrArgs;
1765 std::optional<MapPrintArgs> useDevicePtrArgs;
1774 UnitAttr needsBarrier =
nullptr) {
1775 if (argsSubrange.empty())
1778 p << clauseName <<
"(";
1782 symbols = ArrayAttr::get(ctx, values);
1796 llvm::interleaveComma(
1797 llvm::zip_equal(operands, argsSubrange, symbols, mapIndices.asArrayRef(),
1798 byref.asArrayRef()),
1800 auto [op, arg, sym, map, isByRef] = t;
1802 ReductionModifier mod =
1803 cast<ReductionModifierAttr>(modifier[index]).getValue();
1804 if (mod != ReductionModifier::defaultmod)
1805 p << stringifyReductionModifier(mod) <<
" ";
1812 p << op <<
" -> " << arg;
1814 p <<
" [map_idx=" << map <<
"]";
1817 llvm::interleaveComma(types, p);
1825 StringRef clauseName,
ValueRange argsSubrange,
1826 std::optional<MapPrintArgs> mapArgs) {
1833 StringRef clauseName,
ValueRange argsSubrange,
1834 std::optional<PrivatePrintArgs> privateArgs) {
1837 p, ctx, clauseName, argsSubrange, privateArgs->vars, privateArgs->types,
1838 privateArgs->syms, privateArgs->mapIndices,
nullptr,
1839 nullptr, privateArgs->needsBarrier);
1845 std::optional<ReductionPrintArgs> reductionArgs) {
1848 reductionArgs->vars, reductionArgs->types,
1849 reductionArgs->syms,
nullptr,
1850 reductionArgs->byref, reductionArgs->modifier);
1854 StringRef clauseName,
ValueRange argsSubrange,
1855 std::optional<LinearPrintArgs> linearArgs) {
1856 if (!linearArgs || argsSubrange.empty())
1859 p << clauseName <<
"(";
1860 for (
auto [i, var] : llvm::enumerate(linearArgs->vars)) {
1864 linearArgs->modifiers
1865 ? dyn_cast_if_present<LinearModifierAttr>(linearArgs->modifiers[i])
1868 p << stringifyLinearModifier(modifier.getValue()) <<
"(";
1869 if (linearArgs->syms)
1870 p << linearArgs->syms[i] <<
" ";
1871 p << var <<
" -> " << argsSubrange[i] <<
" : " << linearArgs->types[i]
1872 <<
" = " << linearArgs->stepVars[i] <<
" : " << linearArgs->stepTypes[i];
1878 if (linearArgs->varTypes)
1879 p <<
"linear_var_types(" << linearArgs->varTypes <<
") ";
1883 const AllRegionPrintArgs &args) {
1884 auto iface = llvm::cast<mlir::omp::BlockArgOpenMPOpInterface>(op);
1888 iface.getHasDeviceAddrBlockArgs(),
1889 args.hasDeviceAddrArgs);
1893 args.inReductionArgs);
1901 args.reductionArgs);
1903 iface.getTaskReductionBlockArgs(),
1904 args.taskReductionArgs);
1906 iface.getUseDeviceAddrBlockArgs(),
1907 args.useDeviceAddrArgs);
1909 iface.getUseDevicePtrBlockArgs(), args.useDevicePtrArgs);
1923 UnitAttr privateNeedsBarrier,
1925 AllRegionPrintArgs args;
1926 args.hasDeviceAddrArgs.emplace(hasDeviceAddrVars, hasDeviceAddrTypes);
1927 args.hostEvalArgs.emplace(hostEvalVars, hostEvalTypes);
1928 args.mapArgs.emplace(mapVars, mapTypes);
1929 args.privateArgs.emplace(privateVars, privateTypes, privateSyms,
1930 privateNeedsBarrier, privateMaps);
1938 ArrayAttr privateSyms, UnitAttr privateNeedsBarrier) {
1939 AllRegionPrintArgs args;
1940 args.inReductionArgs.emplace(inReductionVars, inReductionTypes,
1941 inReductionByref, inReductionSyms);
1942 args.privateArgs.emplace(privateVars, privateTypes, privateSyms,
1943 privateNeedsBarrier,
1952 ArrayAttr privateSyms, UnitAttr privateNeedsBarrier,
1955 AllRegionPrintArgs args;
1956 args.inReductionArgs.emplace(inReductionVars, inReductionTypes,
1957 inReductionByref, inReductionSyms);
1958 args.privateArgs.emplace(privateVars, privateTypes, privateSyms,
1959 privateNeedsBarrier,
1961 args.reductionArgs.emplace(reductionVars, reductionTypes, reductionByref,
1962 reductionSyms, reductionMods);
1969 UnitAttr privateNeedsBarrier) {
1970 AllRegionPrintArgs args;
1971 args.privateArgs.emplace(privateVars, privateTypes, privateSyms,
1972 privateNeedsBarrier,
1982 AllRegionPrintArgs args;
1983 args.privateArgs.emplace(privateVars, privateTypes, privateSyms,
1984 privateNeedsBarrier,
1986 args.reductionArgs.emplace(reductionVars, reductionTypes, reductionByref,
1987 reductionSyms, reductionMods);
1996 UnitAttr privateNeedsBarrier,
ArrayAttr reductionMods,
1999 AllRegionPrintArgs args;
2000 args.linearArgs.emplace(linearVars, linearTypes, linearStepVars,
2001 linearStepTypes, linearVarTypes, linearModifiers,
2003 args.privateArgs.emplace(privateVars, privateTypes, privateSyms,
2004 privateNeedsBarrier,
2006 args.reductionArgs.emplace(reductionVars, reductionTypes, reductionByref,
2007 reductionSyms, reductionMods);
2017 AllRegionPrintArgs args;
2018 args.taskReductionArgs.emplace(taskReductionVars, taskReductionTypes,
2019 taskReductionByref, taskReductionSyms);
2029 AllRegionPrintArgs args;
2030 args.useDeviceAddrArgs.emplace(useDeviceAddrVars, useDeviceAddrTypes);
2031 args.useDevicePtrArgs.emplace(useDevicePtrVars, useDevicePtrTypes);
2035template <
typename ParsePrefixFn>
2044 if (failed(parsePrefix()))
2052 if (llvm::isa<mlir::omp::IteratedType>(ty)) {
2053 iteratedVars.push_back(v);
2054 iteratedTypes.push_back(ty);
2056 plainVars.push_back(v);
2057 plainTypes.push_back(ty);
2063template <
typename Pr
intPrefixFn>
2067 PrintPrefixFn &&printPrefixForPlain,
2068 PrintPrefixFn &&printPrefixForIterated) {
2075 p << v <<
" : " << t;
2079 for (
unsigned i = 0; i < iteratedVars.size(); ++i)
2080 emit(iteratedVars[i], iteratedTypes[i], printPrefixForIterated);
2081 for (
unsigned i = 0; i < plainVars.size(); ++i)
2082 emit(plainVars[i], plainTypes[i], printPrefixForPlain);
2089 if (reductionMods && reductionMods.size() != reductionVars.size())
2091 "expected as many reduction modifiers as reduction variables");
2103 if (!reductionVars.empty()) {
2104 if (!reductionSyms || reductionSyms->size() != reductionVars.size())
2106 <<
"expected as many reduction symbol references "
2107 "as reduction variables";
2108 if (reductionByref && reductionByref->size() != reductionVars.size())
2109 return op->
emitError() <<
"expected as many reduction variable by "
2110 "reference attributes as reduction variables";
2113 return op->
emitOpError() <<
"unexpected reduction symbol references";
2120 for (
auto args : llvm::zip(reductionVars, *reductionSyms)) {
2121 Value accum = std::get<0>(args);
2123 if (!accumulators.insert(accum).second)
2124 return op->
emitOpError() <<
"accumulator variable used more than once";
2127 auto symbolRef = llvm::cast<SymbolRefAttr>(std::get<1>(args));
2131 return op->
emitOpError() <<
"expected symbol reference " << symbolRef
2132 <<
" to point to a reduction declaration";
2134 if (decl.getAccumulatorType() && decl.getAccumulatorType() != varType)
2136 <<
"expected accumulator (" << varType
2137 <<
") to be the same type as reduction declaration ("
2138 << decl.getAccumulatorType() <<
")";
2157 if (parser.parseOperand(copyprivateVars.emplace_back()) ||
2158 parser.parseArrow() ||
2159 parser.parseAttribute(symsVec.emplace_back()) ||
2160 parser.parseColonType(copyprivateTypes.emplace_back()))
2166 copyprivateSyms = ArrayAttr::get(parser.
getContext(), syms);
2174 std::optional<ArrayAttr> copyprivateSyms) {
2175 if (!copyprivateSyms.has_value())
2177 llvm::interleaveComma(
2178 llvm::zip(copyprivateVars, *copyprivateSyms, copyprivateTypes), p,
2179 [&](
const auto &args) {
2180 p << std::get<0>(args) <<
" -> " << std::get<1>(args) <<
" : "
2181 << std::get<2>(args);
2188 std::optional<ArrayAttr> copyprivateSyms) {
2189 size_t copyprivateSymsSize =
2190 copyprivateSyms.has_value() ? copyprivateSyms->size() : 0;
2191 if (copyprivateSymsSize != copyprivateVars.size())
2192 return op->
emitOpError() <<
"inconsistent number of copyprivate vars (= "
2193 << copyprivateVars.size()
2194 <<
") and functions (= " << copyprivateSymsSize
2195 <<
"), both must be equal";
2196 if (!copyprivateSyms.has_value())
2199 for (
auto copyprivateVarAndSym :
2200 llvm::zip(copyprivateVars, *copyprivateSyms)) {
2202 llvm::cast<SymbolRefAttr>(std::get<1>(copyprivateVarAndSym));
2203 std::optional<std::variant<mlir::func::FuncOp, mlir::LLVM::LLVMFuncOp>>
2205 if (mlir::func::FuncOp mlirFuncOp =
2208 funcOp = mlirFuncOp;
2209 else if (mlir::LLVM::LLVMFuncOp llvmFuncOp =
2212 funcOp = llvmFuncOp;
2214 auto getNumArguments = [&] {
2215 return std::visit([](
auto &f) {
return f.getNumArguments(); }, *funcOp);
2218 auto getArgumentType = [&](
unsigned i) {
2219 return std::visit([i](
auto &f) {
return f.getArgumentTypes()[i]; },
2224 return op->
emitOpError() <<
"expected symbol reference " << symbolRef
2225 <<
" to point to a copy function";
2227 if (getNumArguments() != 2)
2229 <<
"expected copy function " << symbolRef <<
" to have 2 operands";
2231 Type argTy = getArgumentType(0);
2232 if (argTy != getArgumentType(1))
2233 return op->
emitOpError() <<
"expected copy function " << symbolRef
2234 <<
" arguments to have the same type";
2236 Type varType = std::get<0>(copyprivateVarAndSym).getType();
2237 if (argTy != varType)
2239 <<
"expected copy function arguments' type (" << argTy
2240 <<
") to be the same as copyprivate variable's type (" << varType
2265 OpAsmParser::UnresolvedOperand operand;
2267 if (parser.parseKeyword(&keyword) || parser.parseArrow() ||
2268 parser.parseOperand(operand) || parser.parseColonType(ty))
2270 std::optional<ClauseTaskDepend> keywordDepend =
2271 symbolizeClauseTaskDepend(keyword);
2275 ClauseTaskDependAttr::get(parser.getContext(), *keywordDepend);
2276 if (llvm::isa<mlir::omp::IteratedType>(ty)) {
2277 iteratedVars.push_back(operand);
2278 iteratedTypes.push_back(ty);
2279 iterKindsVec.push_back(kindAttr);
2281 dependVars.push_back(operand);
2282 dependTypes.push_back(ty);
2283 kindsVec.push_back(kindAttr);
2289 dependKinds = ArrayAttr::get(parser.
getContext(), kinds);
2291 iteratedKinds = ArrayAttr::get(parser.
getContext(), iterKinds);
2298 std::optional<ArrayAttr> dependKinds,
2301 std::optional<ArrayAttr> iteratedKinds) {
2304 std::optional<ArrayAttr> kinds) {
2305 for (
unsigned i = 0, e = vars.size(); i < e; ++i) {
2308 p << stringifyClauseTaskDepend(
2309 llvm::cast<mlir::omp::ClauseTaskDependAttr>((*kinds)[i])
2311 <<
" -> " << vars[i] <<
" : " << types[i];
2315 printEntries(dependVars, dependTypes, dependKinds);
2316 printEntries(iteratedVars, iteratedTypes, iteratedKinds);
2321 std::optional<ArrayAttr> dependKinds,
2323 std::optional<ArrayAttr> iteratedKinds,
2325 if (!dependVars.empty()) {
2326 if (!dependKinds || dependKinds->size() != dependVars.size())
2327 return op->
emitOpError() <<
"expected as many depend values"
2328 " as depend variables";
2330 if (dependKinds && !dependKinds->empty())
2331 return op->
emitOpError() <<
"unexpected depend values";
2334 if (!iteratedVars.empty()) {
2335 if (!iteratedKinds || iteratedKinds->size() != iteratedVars.size())
2336 return op->
emitOpError() <<
"expected as many depend iterated values"
2337 " as depend iterated variables";
2339 if (iteratedKinds && !iteratedKinds->empty())
2340 return op->
emitOpError() <<
"unexpected depend iterated values";
2355 IntegerAttr &hintAttr) {
2356 StringRef hintKeyword;
2362 auto parseKeyword = [&]() -> ParseResult {
2365 if (hintKeyword ==
"uncontended")
2367 else if (hintKeyword ==
"contended")
2369 else if (hintKeyword ==
"nonspeculative")
2371 else if (hintKeyword ==
"speculative")
2375 << hintKeyword <<
" is not a valid hint";
2386 IntegerAttr hintAttr) {
2387 int64_t hint = hintAttr.getInt();
2395 auto bitn = [](
int value,
int n) ->
bool {
return value & (1 << n); };
2397 bool uncontended = bitn(hint, 0);
2398 bool contended = bitn(hint, 1);
2399 bool nonspeculative = bitn(hint, 2);
2400 bool speculative = bitn(hint, 3);
2404 hints.push_back(
"uncontended");
2406 hints.push_back(
"contended");
2408 hints.push_back(
"nonspeculative");
2410 hints.push_back(
"speculative");
2412 llvm::interleaveComma(hints, p);
2419 auto bitn = [](
int value,
int n) ->
bool {
return value & (1 << n); };
2421 bool uncontended = bitn(hint, 0);
2422 bool contended = bitn(hint, 1);
2423 bool nonspeculative = bitn(hint, 2);
2424 bool speculative = bitn(hint, 3);
2426 if (uncontended && contended)
2427 return op->
emitOpError() <<
"the hints omp_sync_hint_uncontended and "
2428 "omp_sync_hint_contended cannot be combined";
2429 if (nonspeculative && speculative)
2430 return op->
emitOpError() <<
"the hints omp_sync_hint_nonspeculative and "
2431 "omp_sync_hint_speculative cannot be combined.";
2442 return (value & flag) == flag;
2450static ParseResult parseMapClause(
OpAsmParser &parser,
2451 ClauseMapFlagsAttr &mapType) {
2452 ClauseMapFlags mapTypeBits = ClauseMapFlags::none;
2455 auto parseTypeAndMod = [&]() -> ParseResult {
2456 StringRef mapTypeMod;
2460 if (mapTypeMod ==
"always")
2461 mapTypeBits |= ClauseMapFlags::always;
2463 if (mapTypeMod ==
"implicit")
2464 mapTypeBits |= ClauseMapFlags::implicit;
2466 if (mapTypeMod ==
"ompx_hold")
2467 mapTypeBits |= ClauseMapFlags::ompx_hold;
2469 if (mapTypeMod ==
"close")
2470 mapTypeBits |= ClauseMapFlags::close;
2472 if (mapTypeMod ==
"present")
2473 mapTypeBits |= ClauseMapFlags::present;
2475 if (mapTypeMod ==
"to")
2476 mapTypeBits |= ClauseMapFlags::to;
2478 if (mapTypeMod ==
"from")
2479 mapTypeBits |= ClauseMapFlags::from;
2481 if (mapTypeMod ==
"tofrom")
2482 mapTypeBits |= ClauseMapFlags::to | ClauseMapFlags::from;
2484 if (mapTypeMod ==
"delete")
2485 mapTypeBits |= ClauseMapFlags::del;
2487 if (mapTypeMod ==
"storage")
2488 mapTypeBits |= ClauseMapFlags::storage;
2490 if (mapTypeMod ==
"return_param")
2491 mapTypeBits |= ClauseMapFlags::return_param;
2493 if (mapTypeMod ==
"private")
2494 mapTypeBits |= ClauseMapFlags::priv;
2496 if (mapTypeMod ==
"literal")
2497 mapTypeBits |= ClauseMapFlags::literal;
2499 if (mapTypeMod ==
"attach")
2500 mapTypeBits |= ClauseMapFlags::attach;
2502 if (mapTypeMod ==
"attach_always")
2503 mapTypeBits |= ClauseMapFlags::attach_always;
2505 if (mapTypeMod ==
"attach_never")
2506 mapTypeBits |= ClauseMapFlags::attach_never;
2508 if (mapTypeMod ==
"attach_auto")
2509 mapTypeBits |= ClauseMapFlags::attach_auto;
2511 if (mapTypeMod ==
"ref_ptr")
2512 mapTypeBits |= ClauseMapFlags::ref_ptr;
2514 if (mapTypeMod ==
"ref_ptee")
2515 mapTypeBits |= ClauseMapFlags::ref_ptee;
2517 if (mapTypeMod ==
"is_device_ptr")
2518 mapTypeBits |= ClauseMapFlags::is_device_ptr;
2520 if (mapTypeMod ==
"target_param")
2521 mapTypeBits |= ClauseMapFlags::target_param;
2538 ClauseMapFlagsAttr mapType) {
2540 ClauseMapFlags mapFlags = mapType.getValue();
2545 mapTypeStrs.push_back(
"always");
2547 mapTypeStrs.push_back(
"implicit");
2549 mapTypeStrs.push_back(
"ompx_hold");
2551 mapTypeStrs.push_back(
"close");
2553 mapTypeStrs.push_back(
"present");
2555 mapTypeStrs.push_back(
"target_param");
2564 mapTypeStrs.push_back(
"tofrom");
2566 mapTypeStrs.push_back(
"from");
2568 mapTypeStrs.push_back(
"to");
2571 mapTypeStrs.push_back(
"delete");
2573 mapTypeStrs.push_back(
"return_param");
2575 mapTypeStrs.push_back(
"storage");
2577 mapTypeStrs.push_back(
"private");
2579 mapTypeStrs.push_back(
"literal");
2581 mapTypeStrs.push_back(
"attach");
2583 mapTypeStrs.push_back(
"attach_always");
2585 mapTypeStrs.push_back(
"attach_never");
2587 mapTypeStrs.push_back(
"attach_auto");
2589 mapTypeStrs.push_back(
"ref_ptr");
2591 mapTypeStrs.push_back(
"ref_ptee");
2593 mapTypeStrs.push_back(
"is_device_ptr");
2594 if (mapFlags == ClauseMapFlags::none)
2595 mapTypeStrs.push_back(
"none");
2597 for (
unsigned int i = 0; i < mapTypeStrs.size(); ++i) {
2598 p << mapTypeStrs[i];
2599 if (i + 1 < mapTypeStrs.size()) {
2605static ParseResult parseMembersIndex(
OpAsmParser &parser,
2609 auto parseIndices = [&]() -> ParseResult {
2614 APInt(64, value,
false)));
2628 memberIdxs.push_back(ArrayAttr::get(parser.
getContext(), values));
2632 if (!memberIdxs.empty())
2633 membersIdx = ArrayAttr::get(parser.
getContext(), memberIdxs);
2643 llvm::interleaveComma(membersIdx, p, [&p](
Attribute v) {
2645 auto memberIdx = cast<ArrayAttr>(v);
2646 llvm::interleaveComma(memberIdx.getValue(), p, [&p](
Attribute v2) {
2647 p << cast<IntegerAttr>(v2).getInt();
2654 VariableCaptureKindAttr mapCaptureType) {
2655 std::string typeCapStr;
2656 llvm::raw_string_ostream typeCap(typeCapStr);
2657 if (mapCaptureType.getValue() == mlir::omp::VariableCaptureKind::ByRef)
2659 if (mapCaptureType.getValue() == mlir::omp::VariableCaptureKind::ByCopy)
2660 typeCap <<
"ByCopy";
2661 if (mapCaptureType.getValue() == mlir::omp::VariableCaptureKind::VLAType)
2662 typeCap <<
"VLAType";
2663 if (mapCaptureType.getValue() == mlir::omp::VariableCaptureKind::This)
2669 VariableCaptureKindAttr &mapCaptureType) {
2670 StringRef mapCaptureKey;
2674 if (mapCaptureKey ==
"This")
2675 mapCaptureType = mlir::omp::VariableCaptureKindAttr::get(
2676 parser.
getContext(), mlir::omp::VariableCaptureKind::This);
2677 if (mapCaptureKey ==
"ByRef")
2678 mapCaptureType = mlir::omp::VariableCaptureKindAttr::get(
2679 parser.
getContext(), mlir::omp::VariableCaptureKind::ByRef);
2680 if (mapCaptureKey ==
"ByCopy")
2681 mapCaptureType = mlir::omp::VariableCaptureKindAttr::get(
2682 parser.
getContext(), mlir::omp::VariableCaptureKind::ByCopy);
2683 if (mapCaptureKey ==
"VLAType")
2684 mapCaptureType = mlir::omp::VariableCaptureKindAttr::get(
2685 parser.
getContext(), mlir::omp::VariableCaptureKind::VLAType);
2691 Operation *op, mlir::omp::MapInfoOp mapInfoOp,
2695 mlir::omp::ClauseMapFlags mapTypeBits = mapInfoOp.getMapType();
2698 bool from =
mapTypeToBool(mapTypeBits, ClauseMapFlags::from);
2701 bool always =
mapTypeToBool(mapTypeBits, ClauseMapFlags::always);
2702 bool close =
mapTypeToBool(mapTypeBits, ClauseMapFlags::close);
2703 bool implicit =
mapTypeToBool(mapTypeBits, ClauseMapFlags::implicit);
2704 bool attach =
mapTypeToBool(mapTypeBits, ClauseMapFlags::attach);
2706 if ((isa<TargetDataOp>(op) || isa<TargetOp>(op)) && del)
2708 "to, from, tofrom and alloc map types are permitted");
2710 if (isa<TargetEnterDataOp>(op) && (from || del))
2711 return emitError(op->
getLoc(),
"to and alloc map types are permitted");
2713 if (isa<TargetExitDataOp>(op) && to)
2715 "from, release and delete map types are permitted");
2717 if (isa<TargetUpdateOp>(op)) {
2720 "at least one of to or from map types must be "
2721 "specified, other map types are not permitted");
2724 if (!to && !from && !attach) {
2726 "at least one of to or from or attach map types must be "
2727 "specified, other map types are not permitted");
2730 auto updateVar = mapInfoOp.getVarPtr();
2732 if ((to && from) || (to && updateFromVars.contains(updateVar)) ||
2733 (from && updateToVars.contains(updateVar))) {
2736 "either to or from map types can be specified, not both");
2739 if (always || close || implicit) {
2742 "present, mapper and iterator map type modifiers are permitted");
2748 to ? updateToVars.insert(updateVar) : updateFromVars.insert(updateVar);
2752 if ((mapInfoOp.getVarPtrPtr() && !mapInfoOp.getVarPtrPtrType()) ||
2753 (!mapInfoOp.getVarPtrPtr() && mapInfoOp.getVarPtrPtrType())) {
2755 "if varPtrPtr or varPtrPtrType is specified, then both "
2767 for (
auto mapOp : mapVars) {
2768 if (!mapOp.getDefiningOp())
2771 if (
auto mapInfoOp = mapOp.getDefiningOp<mlir::omp::MapInfoOp>()) {
2775 }
else if (!isa<DeclareMapperInfoOp>(op)) {
2777 "map argument is not a map entry operation");
2782 for (
auto iterVal : mapIterated) {
2783 auto iterOp = iterVal.getDefiningOp<mlir::omp::IteratorOp>();
2785 return op->
emitOpError() <<
"'map_iterated' arguments must be defined by "
2786 "'omp.iterator' ops";
2789 mlir::omp::YieldOp yieldOp = iterOp.getYieldOp();
2790 auto yieldedMapInfo =
2791 yieldOp && yieldOp.getNumOperands() == 1
2792 ? yieldOp.getResults()[0].getDefiningOp<mlir::omp::MapInfoOp>()
2794 if (!yieldedMapInfo)
2795 return op->
emitOpError() <<
"'map_iterated' iterator body must yield "
2796 "a value defined by 'omp.map.info'";
2806template <
typename OpType>
2810 std::optional<DenseI64ArrayAttr> privateMapIndices =
2811 targetOp.getPrivateMapsAttr();
2814 if (!privateMapIndices.has_value() || !privateMapIndices.value())
2819 if (privateMapIndices.value().size() !=
2820 static_cast<int64_t>(privateVars.size()))
2821 return emitError(targetOp.getLoc(),
"sizes of `private` operand range and "
2822 "`private_maps` attribute mismatch");
2832 StringRef clauseName,
2834 for (
Value var : vars)
2835 if (!llvm::isa_and_present<MapInfoOp>(var.getDefiningOp()))
2837 <<
"'" << clauseName
2838 <<
"' arguments must be defined by 'omp.map.info' ops";
2842LogicalResult MapInfoOp::verify() {
2843 if (getMapperId() &&
2845 *
this, getMapperIdAttr())) {
2860 const TargetDataOperands &clauses) {
2861 TargetDataOp::build(builder, state, clauses.device, clauses.ifExpr,
2862 clauses.mapVars, clauses.mapIterated,
2863 clauses.useDeviceAddrVars, clauses.useDevicePtrVars);
2866LogicalResult TargetDataOp::verify() {
2867 if (getMapVars().empty() && getMapIterated().empty() &&
2868 getUseDevicePtrVars().empty() && getUseDeviceAddrVars().empty()) {
2869 return ::emitError(this->getLoc(),
2870 "At least one of map, use_device_ptr_vars, or "
2871 "use_device_addr_vars operand must be present");
2875 getUseDevicePtrVars())))
2879 getUseDeviceAddrVars())))
2885void TargetDataOp::getSuccessorRegions(
2898void TargetEnterDataOp::build(
2902 TargetEnterDataOp::build(
2904 clauses.dependVars,
makeArrayAttr(ctx, clauses.dependIteratedKinds),
2905 clauses.dependIterated, clauses.device, clauses.ifExpr, clauses.mapVars,
2906 clauses.mapIterated, clauses.nowait);
2909LogicalResult TargetEnterDataOp::verify() {
2910 LogicalResult verifyDependVars =
2912 getDependIteratedKinds(), getDependIterated());
2913 return failed(verifyDependVars)
2925 TargetExitDataOp::build(
2927 clauses.dependVars,
makeArrayAttr(ctx, clauses.dependIteratedKinds),
2928 clauses.dependIterated, clauses.device, clauses.ifExpr, clauses.mapVars,
2929 clauses.mapIterated, clauses.nowait);
2932LogicalResult TargetExitDataOp::verify() {
2933 LogicalResult verifyDependVars =
2935 getDependIteratedKinds(), getDependIterated());
2936 return failed(verifyDependVars)
2948 TargetUpdateOp::build(builder, state,
makeArrayAttr(ctx, clauses.dependKinds),
2951 clauses.dependIterated, clauses.device, clauses.ifExpr,
2952 clauses.mapVars, clauses.mapIterated, clauses.nowait);
2955LogicalResult TargetUpdateOp::verify() {
2956 LogicalResult verifyDependVars =
2958 getDependIteratedKinds(), getDependIterated());
2959 return failed(verifyDependVars)
2972 builder, state, clauses.allocateVars, clauses.allocatorVars,
2975 makeArrayAttr(ctx, clauses.dependKinds), clauses.dependVars,
2976 makeArrayAttr(ctx, clauses.dependIteratedKinds), clauses.dependIterated,
2977 clauses.device, clauses.dynGroupprivateAccessGroup,
2978 clauses.dynGroupprivateFallback, clauses.dynGroupprivateSize,
2979 clauses.hasDeviceAddrVars, clauses.hostEvalVars, clauses.ifExpr,
2980 clauses.inReductionVars,
2982 makeArrayAttr(ctx, clauses.inReductionSyms), clauses.isDevicePtrVars,
2983 clauses.mapVars, clauses.mapIterated, clauses.nowait, clauses.privateVars,
2984 makeArrayAttr(ctx, clauses.privateSyms), clauses.privateNeedsBarrier,
2985 clauses.threadLimitVars,
nullptr, clauses.
kernelType);
2988bool TargetOp::hasHostEvalTripCount() {
2989 TargetExecMode mode = getKernelType();
2990 if (mode == TargetExecMode::spmd || mode == TargetExecMode::spmd_no_loop)
2993 if (mode == TargetExecMode::bare)
2999 cast<ComposableOpInterface>(getOperation()).findCapturedOp();
3000 if (
auto loopNestOp = dyn_cast_if_present<LoopNestOp>(capturedOp)) {
3002 loopNestOp.gatherWrappers(loopWrappers);
3004 LoopWrapperInterface *innermostWrapper = loopWrappers.begin();
3005 if (isa<SimdOp>(innermostWrapper))
3006 innermostWrapper = std::next(innermostWrapper);
3008 auto numWrappers = std::distance(innermostWrapper, loopWrappers.end());
3009 if (numWrappers != 1)
3012 if (!isa<DistributeOp>(innermostWrapper))
3016 if (isa_and_present<TeamsOp>(parentOp) &&
3032 if (mapVarPtr == inReductionVar)
3038LogicalResult TargetOp::verify() {
3040 getOperation(), getAllocateVars(), getAllocatorVars(),
3041 getAllocateAlignmentsAttr(), getAllocatePrivateIndicesAttr(),
3042 getPrivateVars(), getPrivateSymsAttr())))
3045 if (getKernelType() == TargetExecMode::bare && !isCombined())
3046 return emitOpError() <<
"bare kernel requires 'omp.combined'";
3049 getDependIteratedKinds(),
3050 getDependIterated())))
3054 getHasDeviceAddrVars())))
3061 *
this, getDynGroupprivateAccessGroupAttr(),
3062 getDynGroupprivateFallbackAttr(), getDynGroupprivateSize())))
3069 getInReductionVars(),
3070 getInReductionByref())))
3078 for (
Value inReductionVar : getInReductionVars()) {
3079 bool captured =
false;
3080 for (
Value mapVar : getMapVars()) {
3081 auto mapInfo = mapVar.getDefiningOp<MapInfoOp>();
3088 return emitOpError() <<
"in_reduction variable must be captured by a "
3089 "matching map_entries entry";
3095LogicalResult TargetOp::verifyRegions() {
3096 auto teamsOps = getOps<TeamsOp>();
3097 auto numNestedTeams = std::distance(teamsOps.begin(), teamsOps.end());
3098 if (numNestedTeams > 1)
3099 return emitError(
"target containing multiple 'omp.teams' nested ops");
3101 if (numNestedTeams == 0) {
3102 switch (getKernelType()) {
3103 case TargetExecMode::bare:
3104 return emitOpError()
3105 <<
"bare kernel must contain a nested 'omp.teams' operation";
3106 case TargetExecMode::spmd_no_loop:
3107 return emitOpError() <<
"spmd_no_loop kernel must contain a nested "
3108 "'omp.teams' operation";
3115 cast<ComposableOpInterface>(getOperation()).findCapturedOp();
3116 if ((getKernelType() == TargetExecMode::spmd ||
3117 getKernelType() == TargetExecMode::spmd_no_loop) &&
3118 !isa_and_present<LoopNestOp>(capturedOp))
3119 return emitOpError()
3120 <<
"SPMD kernel must capture an 'omp.loop_nest' operation";
3122 bool isTargetDevice =
false;
3123 if (
auto offloadMod = (*this)->getParentOfType<OffloadModuleInterface>())
3124 if (offloadMod.getIsTargetDevice())
3125 isTargetDevice =
true;
3129 cast<BlockArgOpenMPOpInterface>(getOperation()).getHostEvalBlockArgs();
3131 bool hostEvalTripCount = hasHostEvalTripCount();
3132 for (
Value hostEvalArg : hostEvalBlockArgs) {
3134 if (
auto teamsOp = dyn_cast<TeamsOp>(user)) {
3136 if (hostEvalArg == teamsOp.getNumTeamsLower() ||
3137 llvm::is_contained(teamsOp.getNumTeamsUpperVars(), hostEvalArg) ||
3138 llvm::is_contained(teamsOp.getThreadLimitVars(), hostEvalArg))
3141 return emitOpError() <<
"host_eval argument only legal as 'num_teams' "
3142 "and 'thread_limit' in 'omp.teams'";
3144 if (
auto parallelOp = dyn_cast<ParallelOp>(user)) {
3145 if (llvm::is_contained(parallelOp.getNumThreadsVars(), hostEvalArg))
3148 return emitOpError()
3149 <<
"host_eval argument only legal as 'num_threads' in "
3152 if (
auto loopNestOp = dyn_cast<LoopNestOp>(user)) {
3153 if (hostEvalTripCount &&
3154 (llvm::is_contained(loopNestOp.getLoopLowerBounds(), hostEvalArg) ||
3155 llvm::is_contained(loopNestOp.getLoopUpperBounds(), hostEvalArg) ||
3156 llvm::is_contained(loopNestOp.getLoopSteps(), hostEvalArg)))
3159 return emitOpError() <<
"host_eval argument only legal as loop bounds "
3160 "and steps in 'omp.loop_nest' when trip count "
3161 "must be evaluated in the host";
3164 return emitOpError() <<
"host_eval argument illegal use in '"
3165 << user->getName() <<
"' operation";
3169 if (hostEvalTripCount && !isTargetDevice) {
3170 auto loopOp = cast<LoopNestOp>(capturedOp);
3171 for (
auto arg : llvm::concat<Value>(loopOp.getLoopLowerBounds(),
3172 loopOp.getLoopUpperBounds(),
3173 loopOp.getLoopSteps())) {
3174 if (!llvm::is_contained(hostEvalBlockArgs, arg))
3175 return emitOpError() <<
"nested 'omp.loop_nest' bounds expected to "
3176 "be host-evaluated";
3194 return getHostEvalVars();
3200 assert(successor == &getRegion());
3201 return mlir::cast<BlockArgOpenMPOpInterface>(getOperation())
3202 .getHostEvalBlockArgs();
3211 ParallelOp::build(builder, state,
ValueRange(),
3226 const ParallelOperands &clauses) {
3228 ParallelOp::build(builder, state, clauses.allocateVars, clauses.allocatorVars,
3231 clauses.ifExpr, clauses.numThreadsVars, clauses.privateVars,
3233 clauses.privateNeedsBarrier, clauses.procBindKind,
3235 clauses.reductionVars,
3240template <
typename OpType>
3242 auto privateVars = op.getPrivateVars();
3243 auto privateSyms = op.getPrivateSymsAttr();
3245 if (privateVars.empty() && (privateSyms ==
nullptr || privateSyms.empty()))
3248 auto numPrivateVars = privateVars.size();
3249 auto numPrivateSyms = (privateSyms ==
nullptr) ? 0 : privateSyms.size();
3251 if (numPrivateVars != numPrivateSyms)
3252 return op.emitError() <<
"inconsistent number of private variables and "
3253 "privatizer op symbols, private vars: "
3255 <<
" vs. privatizer op symbols: " << numPrivateSyms;
3257 for (
auto privateVarInfo : llvm::zip_equal(privateVars, privateSyms)) {
3258 Type varType = std::get<0>(privateVarInfo).getType();
3259 SymbolRefAttr privateSym = cast<SymbolRefAttr>(std::get<1>(privateVarInfo));
3260 PrivateClauseOp privatizerOp =
3263 if (privatizerOp ==
nullptr)
3264 return op.emitError() <<
"failed to lookup privatizer op with symbol: '"
3265 << privateSym <<
"'";
3267 Type privatizerType = privatizerOp.getArgType();
3269 if (privatizerType && (varType != privatizerType))
3270 return op.emitError()
3271 <<
"type mismatch between a "
3272 << stringifyDataSharingClauseType(
3273 privatizerOp.getDataSharingType())
3274 <<
" variable and its privatizer op, var type: " << varType
3275 <<
" vs. privatizer op type: " << privatizerType;
3277 if (privatizerOp.getDataSharingType() == DataSharingClauseType::Linear)
3278 return op.emitError() <<
"`linear` privatizer '" << privateSym
3279 <<
"' can only be used in a `linear` clause";
3286template <
typename OpType>
3289 std::optional<ArrayAttr> linearSyms = op.getLinearSyms();
3290 if (linearVars.empty() && (!linearSyms || linearSyms->empty()))
3293 if (!linearSyms || linearSyms->size() != linearVars.size())
3294 return op.emitOpError()
3295 <<
"expected as many linear privatizers as linear variables";
3297 for (
auto [var, sym] : llvm::zip_equal(linearVars, *linearSyms)) {
3298 auto symRef = cast<SymbolRefAttr>(sym);
3302 return op.emitOpError() <<
"failed to lookup privatizer op with symbol: '"
3304 if (privatizer.getDataSharingType() != DataSharingClauseType::Linear)
3305 return op.emitOpError() <<
"privatizer '" << symRef
3306 <<
"' of a linear variable must be `linear`";
3307 Type argType = privatizer.getArgType();
3308 if (argType && argType != var.getType())
3309 return op.emitOpError()
3310 <<
"type mismatch between a linear variable and its privatizer "
3312 << var.getType() <<
" vs. privatizer op type: " << argType;
3317LogicalResult ParallelOp::verify() {
3321 getOperation(), getAllocateVars(), getAllocatorVars(),
3322 getAllocateAlignmentsAttr(), getAllocatePrivateIndicesAttr(),
3323 getPrivateVars(), getPrivateSymsAttr(),
3328 getReductionByref(), getReductionModsAttr());
3331LogicalResult ParallelOp::verifyRegions() {
3332 auto distChildOps = getOps<DistributeOp>();
3333 int numDistChildOps = std::distance(distChildOps.begin(), distChildOps.end());
3334 if (numDistChildOps > 1)
3336 <<
"multiple 'omp.distribute' nested inside of 'omp.parallel'";
3338 if (numDistChildOps == 1) {
3341 <<
"'omp.composite' attribute missing from composite operation";
3343 auto *ompDialect =
getContext()->getLoadedDialect<OpenMPDialect>();
3344 Operation &distributeOp = **distChildOps.begin();
3346 if (&childOp == &distributeOp || ompDialect != childOp.getDialect())
3350 return emitError() <<
"unexpected OpenMP operation inside of composite "
3352 << childOp.getName();
3354 }
else if (isComposite()) {
3356 <<
"'omp.composite' attribute present in non-composite operation";
3373 const TeamsOperands &clauses) {
3377 builder, state, clauses.allocateVars, clauses.allocatorVars,
3380 clauses.dynGroupprivateAccessGroup, clauses.dynGroupprivateFallback,
3381 clauses.dynGroupprivateSize, clauses.ifExpr, clauses.numTeamsLower,
3382 clauses.numTeamsUpperVars, {},
nullptr,
3384 makeArrayAttr(ctx, clauses.reductionMods), clauses.reductionVars,
3386 makeArrayAttr(ctx, clauses.reductionSyms), clauses.threadLimitVars);
3393 if (numTeamsLower) {
3394 if (numTeamsUpperVars.size() != 1)
3396 "expected exactly one num_teams upper bound when lower bound is "
3400 "expected num_teams upper bound and lower bound to be "
3407LogicalResult TeamsOp::verify() {
3414 auto parentTarget = llvm::dyn_cast_if_present<TargetOp>(op->
getParentOp());
3416 return emitError(
"expected to be nested inside of omp.target or not nested "
3417 "in any OpenMP dialect operations");
3421 this->getNumTeamsUpperVars())))
3425 parentTarget.getKernelType() == TargetExecMode::spmd_no_loop &&
3426 (getNumTeamsLower() || !getNumTeamsUpperVars().empty()))
3427 return emitOpError() <<
"'num_teams' not allowed in SPMD-no-loop kernels";
3430 getOperation(), getAllocateVars(), getAllocatorVars(),
3431 getAllocateAlignmentsAttr(), getAllocatePrivateIndicesAttr(),
3432 getPrivateVars(), getPrivateSymsAttr())))
3436 op, getDynGroupprivateAccessGroupAttr(),
3437 getDynGroupprivateFallbackAttr(), getDynGroupprivateSize())))
3444 getReductionByref(), getReductionModsAttr());
3452 return getParentOp().getPrivateVars();
3456 return getParentOp().getReductionVars();
3464 const SectionsOperands &clauses) {
3467 SectionsOp::build(builder, state, clauses.allocateVars, clauses.allocatorVars,
3474 clauses.reductionVars,
3480LogicalResult SectionsOp::verify() {
3482 return emitOpError() <<
"cannot be a non-innermost combined construct leaf";
3485 getOperation(), getAllocateVars(), getAllocatorVars(),
3486 getAllocateAlignmentsAttr(), getAllocatePrivateIndicesAttr(),
3487 getPrivateVars(), getPrivateSymsAttr())))
3491 getReductionByref(), getReductionModsAttr());
3494LogicalResult SectionsOp::verifyRegions() {
3495 for (
auto &inst : *getRegion().begin()) {
3496 if (!(isa<SectionOp>(inst) || isa<TerminatorOp>(inst))) {
3497 return emitOpError()
3498 <<
"expected omp.section op or terminator op inside region";
3518 auto iface = dyn_cast<BlockArgOpenMPOpInterface>(op);
3536 auto iface = dyn_cast<BlockArgOpenMPOpInterface>(op);
3554 addEffects(iface.getReductionVars(), iface.getReductionBlockArgs());
3555 addEffects(iface.getInReductionVars(), iface.getInReductionBlockArgs());
3565void SectionsOp::getEffects(
3574 bool hasUnknownRecipeEffects =
3575 (!getPrivateVars().empty() && !getPrivateAssumeBoundedRecipeEffects()) ||
3576 (!getReductionVars().empty() &&
3577 !getReductionAssumeBoundedRecipeEffects());
3579 if (hasUnknownRecipeEffects) {
3592 const ScopeOperands &clauses) {
3595 builder, state, clauses.allocateVars, clauses.allocatorVars,
3598 clauses.nowait, clauses.privateVars,
3599 makeArrayAttr(ctx, clauses.privateSyms), clauses.privateNeedsBarrier,
3600 makeArrayAttr(ctx, clauses.reductionMods), clauses.reductionVars,
3605LogicalResult ScopeOp::verify() {
3607 getOperation(), getAllocateVars(), getAllocatorVars(),
3608 getAllocateAlignmentsAttr(), getAllocatePrivateIndicesAttr(),
3609 getPrivateVars(), getPrivateSymsAttr(),
3617 getReductionByref(), getReductionModsAttr());
3625 const SingleOperands &clauses) {
3629 builder, state, clauses.allocateVars, clauses.allocatorVars,
3632 clauses.copyprivateVars,
makeArrayAttr(ctx, clauses.copyprivateSyms),
3633 nullptr, clauses.nowait,
3639LogicalResult SingleOp::verify() {
3641 getOperation(), getAllocateVars(), getAllocatorVars(),
3642 getAllocateAlignmentsAttr(), getAllocatePrivateIndicesAttr(),
3643 getPrivateVars(), getPrivateSymsAttr())))
3647 getCopyprivateSyms());
3650void SingleOp::getEffects(
3659 bool hasUnknownRecipeEffects =
3660 (!getPrivateVars().empty() && !getPrivateAssumeBoundedRecipeEffects()) ||
3661 (!getCopyprivateVars().empty() &&
3662 !getCopyprivateAssumeBoundedRecipeEffects());
3663 if (hasUnknownRecipeEffects) {
3683 const WorkshareOperands &clauses) {
3684 WorkshareOp::build(builder, state, clauses.nowait);
3687LogicalResult WorkshareOp::verify() {
3689 return emitOpError() <<
"cannot be a non-innermost combined construct leaf";
3698LogicalResult WorkshareLoopWrapperOp::verifyRegions() {
3699 if (isa_and_nonnull<LoopWrapperInterface>((*this)->getParentOp()) ||
3701 return emitOpError() <<
"expected to be a standalone loop wrapper";
3710LogicalResult LoopWrapperInterface::verifyImpl() {
3714 return emitOpError() <<
"loop wrapper must also have the `NoTerminator` "
3715 "and `SingleBlock` traits";
3718 return emitOpError() <<
"loop wrapper does not contain exactly one region";
3721 if (range_size(region.
getOps()) != 1)
3722 return emitOpError()
3723 <<
"loop wrapper does not contain exactly one nested op";
3726 if (!isa<LoopNestOp, LoopWrapperInterface>(firstOp))
3727 return emitOpError() <<
"nested in loop wrapper is not another loop "
3728 "wrapper or `omp.loop_nest`";
3737Operation *ComposableOpInterface::findCapturedOp() {
3741 if (
auto wrapperOp = dyn_cast<LoopWrapperInterface>(op))
3742 return wrapperOp.getWrappedLoop();
3747 if (!isCombined() && !isComposite())
3752 if (
auto wrapperOp = dyn_cast<LoopWrapperInterface>(&nestedOp))
3753 return wrapperOp.getWrappedLoop();
3755 if (
auto composableOp = dyn_cast<ComposableOpInterface>(&nestedOp))
3756 return composableOp.findCapturedOp();
3765LogicalResult ComposableOpInterface::verifyImpl() {
3769 return emitOpError() <<
"composable ops must have a single region";
3771 if (isComposite() && !isa<LoopWrapperInterface, ParallelOp>(op))
3772 return emitOpError() <<
"non-loop wrapper cannot be composite";
3778 auto count = llvm::count_if(
3780 if (isa<ComposableOpInterface, LoopWrapperInterface>(op)) {
3801 return emitOpError()
3802 <<
"multiple eligible child ops found in combined op";
3813 if (successor->isReachable(parentBlock))
3814 return emitOpError() <<
"nested combined child op is part of a loop";
3818 !domInfo.
dominates(parentBlock, &block))
3819 return emitOpError()
3820 <<
"nested combined child op doesn't unconditionally execute";
3830 const LoopOperands &clauses) {
3833 LoopOp::build(builder, state, clauses.bindKind, clauses.privateVars,
3835 clauses.privateNeedsBarrier, clauses.order, clauses.orderMod,
3837 clauses.reductionVars,
3842LogicalResult LoopOp::verify() {
3847 getReductionByref(), getReductionModsAttr());
3850LogicalResult LoopOp::verifyRegions() {
3851 if (llvm::isa_and_nonnull<LoopWrapperInterface>((*this)->getParentOp()) ||
3853 return emitOpError() <<
"expected to be a standalone loop wrapper";
3864 build(builder, state, {}, {},
3869 nullptr,
false,
nullptr,
3871 nullptr, {},
nullptr,
3882 const WsloopOperands &clauses) {
3885 builder, state, clauses.allocateVars, clauses.allocatorVars,
3888 clauses.linearVars, clauses.linearStepVars, clauses.linearVarTypes,
3889 clauses.linearModifiers,
makeArrayAttr(ctx, clauses.linearSyms),
3890 clauses.nowait, clauses.order, clauses.orderMod, clauses.ordered,
3891 clauses.privateVars,
makeArrayAttr(ctx, clauses.privateSyms),
3892 clauses.privateNeedsBarrier,
makeArrayAttr(ctx, clauses.reductionMods),
3893 clauses.reductionVars,
3895 makeArrayAttr(ctx, clauses.reductionSyms), clauses.scheduleKind,
3896 clauses.scheduleChunk, clauses.scheduleMod, clauses.scheduleSimd);
3899LogicalResult WsloopOp::verify() {
3901 getOperation(), getAllocateVars(), getAllocatorVars(),
3902 getAllocateAlignmentsAttr(), getAllocatePrivateIndicesAttr(),
3903 getPrivateVars(), getPrivateSymsAttr())))
3909 if (getLinearVars().size() &&
3910 getLinearVarTypes().value().size() != getLinearVars().size())
3911 return emitError() <<
"Ill-formed type attributes for linear variables";
3917 getReductionByref(), getReductionModsAttr());
3920LogicalResult WsloopOp::verifyRegions() {
3921 bool isCompositeChildLeaf =
3922 llvm::dyn_cast_if_present<LoopWrapperInterface>((*this)->getParentOp());
3924 if (LoopWrapperInterface nested = getNestedWrapper()) {
3927 <<
"'omp.composite' attribute missing from composite wrapper";
3931 if (!isa<SimdOp>(nested))
3932 return emitError() <<
"only supported nested wrapper is 'omp.simd'";
3934 }
else if (isComposite() && !isCompositeChildLeaf) {
3936 <<
"'omp.composite' attribute present in non-composite wrapper";
3937 }
else if (!isComposite() && isCompositeChildLeaf) {
3939 <<
"'omp.composite' attribute missing from composite wrapper";
3950 const SimdOperands &clauses) {
3953 builder, state, clauses.alignedVars,
3955 clauses.linearVars, clauses.linearStepVars, clauses.linearVarTypes,
3956 clauses.linearModifiers,
makeArrayAttr(ctx, clauses.linearSyms),
3957 clauses.nontemporalVars, clauses.order, clauses.orderMod,
3958 clauses.privateVars,
makeArrayAttr(ctx, clauses.privateSyms),
3959 clauses.privateNeedsBarrier,
makeArrayAttr(ctx, clauses.reductionMods),
3960 clauses.reductionVars,
3966LogicalResult SimdOp::verify() {
3968 getReductionModsAttr())))
3971 if (getSimdlen().has_value() && getSafelen().has_value() &&
3972 getSimdlen().value() > getSafelen().value())
3973 return emitOpError()
3974 <<
"simdlen clause and safelen clause are both present, but the "
3975 "simdlen value is not less than or equal to safelen value";
3987 bool isCompositeChildLeaf =
3988 llvm::dyn_cast_if_present<LoopWrapperInterface>((*this)->getParentOp());
3990 if (!isComposite() && isCompositeChildLeaf)
3992 <<
"'omp.composite' attribute missing from composite wrapper";
3994 if (isComposite() && !isCompositeChildLeaf)
3996 <<
"'omp.composite' attribute present in non-composite wrapper";
4000 std::optional<ArrayAttr> privateSyms = getPrivateSyms();
4002 for (
const Attribute &sym : *privateSyms) {
4003 auto symRef = cast<SymbolRefAttr>(sym);
4004 omp::PrivateClauseOp privatizer =
4006 getOperation(), symRef);
4008 return emitError() <<
"Cannot find privatizer '" << symRef <<
"'";
4009 if (privatizer.getDataSharingType() ==
4010 DataSharingClauseType::FirstPrivate)
4011 return emitError() <<
"FIRSTPRIVATE cannot be used with SIMD";
4018 if (getLinearVars().size() &&
4019 getLinearVarTypes().value().size() != getLinearVars().size())
4020 return emitError() <<
"Ill-formed type attributes for linear variables";
4028 for (
Value var : getLinearVars()) {
4029 if (privateVars.contains(var) || reductionVars.contains(var))
4030 return emitOpError()
4031 <<
"linear variables cannot appear in other data-sharing clauses";
4037LogicalResult SimdOp::verifyRegions() {
4038 if (getNestedWrapper())
4039 return emitOpError() <<
"must wrap an 'omp.loop_nest' directly";
4049 const DistributeOperands &clauses) {
4050 DistributeOp::build(
4051 builder, state, clauses.allocateVars, clauses.allocatorVars,
4054 clauses.allocatePrivateIndices),
4055 clauses.distScheduleStatic, clauses.distScheduleChunkSize, clauses.order,
4056 clauses.orderMod, clauses.privateVars,
4058 clauses.privateNeedsBarrier);
4061LogicalResult DistributeOp::verify() {
4062 if (this->getDistScheduleChunkSize() && !this->getDistScheduleStatic())
4063 return emitOpError() <<
"chunk size set without "
4064 "dist_schedule_static being present";
4067 getOperation(), getAllocateVars(), getAllocatorVars(),
4068 getAllocateAlignmentsAttr(), getAllocatePrivateIndicesAttr(),
4069 getPrivateVars(), getPrivateSymsAttr())))
4078LogicalResult DistributeOp::verifyRegions() {
4079 if (LoopWrapperInterface nested = getNestedWrapper()) {
4082 <<
"'omp.composite' attribute missing from composite wrapper";
4085 if (isa<WsloopOp>(nested)) {
4087 if (!llvm::dyn_cast_if_present<ParallelOp>(parentOp) ||
4088 !cast<ComposableOpInterface>(parentOp).isComposite()) {
4089 return emitError() <<
"an 'omp.wsloop' nested wrapper is only allowed "
4090 "when a composite 'omp.parallel' is the direct "
4093 }
else if (!isa<SimdOp>(nested))
4094 return emitError() <<
"only supported nested wrappers are 'omp.simd' and "
4096 }
else if (isComposite()) {
4098 <<
"'omp.composite' attribute present in non-composite wrapper";
4109 const DeclareMapperInfoOperands &clauses) {
4110 DeclareMapperInfoOp::build(builder, state, clauses.mapVars,
4111 clauses.mapIterated);
4114LogicalResult DeclareMapperInfoOp::verify() {
4118LogicalResult DeclareMapperOp::verifyRegions() {
4119 if (!llvm::isa_and_present<DeclareMapperInfoOp>(
4120 getRegion().getBlocks().front().getTerminator()))
4121 return emitOpError() <<
"expected terminator to be a DeclareMapperInfoOp";
4130LogicalResult DeclareReductionOp::verifyRegions() {
4131 if (!getAllocRegion().empty()) {
4132 for (YieldOp yieldOp : getAllocRegion().getOps<YieldOp>()) {
4133 if (yieldOp.getResults().size() != 1 ||
4134 yieldOp.getResults().getTypes()[0] !=
getType())
4135 return emitOpError() <<
"expects alloc region to yield a value "
4136 "of the reduction type";
4140 if (getInitializerRegion().empty())
4141 return emitOpError() <<
"expects non-empty initializer region";
4142 Block &initializerEntryBlock = getInitializerRegion().
front();
4145 if (!getAllocRegion().empty())
4146 return emitOpError() <<
"expects two arguments to the initializer region "
4147 "when an allocation region is used";
4149 if (getAllocRegion().empty())
4150 return emitOpError() <<
"expects one argument to the initializer region "
4151 "when no allocation region is used";
4153 return emitOpError()
4154 <<
"expects one or two arguments to the initializer region";
4158 if (arg.getType() !=
getType())
4159 return emitOpError() <<
"expects initializer region argument to match "
4160 "the reduction type";
4162 for (YieldOp yieldOp : getInitializerRegion().getOps<YieldOp>()) {
4163 if (yieldOp.getResults().size() != 1 ||
4164 yieldOp.getResults().getTypes()[0] !=
getType())
4165 return emitOpError() <<
"expects initializer region to yield a value "
4166 "of the reduction type";
4169 if (getReductionRegion().empty())
4170 return emitOpError() <<
"expects non-empty reduction region";
4171 Block &reductionEntryBlock = getReductionRegion().
front();
4176 return emitOpError() <<
"expects reduction region with two arguments of "
4177 "the reduction type";
4178 for (YieldOp yieldOp : getReductionRegion().getOps<YieldOp>()) {
4179 if (yieldOp.getResults().size() != 1 ||
4180 yieldOp.getResults().getTypes()[0] !=
getType())
4181 return emitOpError() <<
"expects reduction region to yield a value "
4182 "of the reduction type";
4185 if (!getAtomicReductionRegion().empty()) {
4186 Block &atomicReductionEntryBlock = getAtomicReductionRegion().
front();
4190 return emitOpError() <<
"expects atomic reduction region with two "
4191 "arguments of the same type";
4192 auto ptrType = llvm::dyn_cast<PointerLikeType>(
4195 (ptrType.getElementType() && ptrType.getElementType() !=
getType()))
4196 return emitOpError() <<
"expects atomic reduction region arguments to "
4197 "be accumulators containing the reduction type";
4200 if (getCleanupRegion().empty())
4202 Block &cleanupEntryBlock = getCleanupRegion().
front();
4205 return emitOpError() <<
"expects cleanup region with one argument "
4206 "of the reduction type";
4216 const TaskOperands &clauses) {
4218 TaskOp::build(builder, state, clauses.iterated, clauses.affinityVars,
4219 clauses.allocateVars, clauses.allocatorVars,
4222 makeArrayAttr(ctx, clauses.dependKinds), clauses.dependVars,
4224 clauses.dependIterated, clauses.final, clauses.ifExpr,
4225 clauses.inReductionVars,
4229 clauses.mergeable, clauses.priority,
4230 clauses.privateVars,
4232 clauses.privateNeedsBarrier,
4234 clauses.threadset, clauses.untied, clauses.eventHandle);
4237LogicalResult TaskOp::verify() {
4239 getOperation(), getAllocateVars(), getAllocatorVars(),
4240 getAllocateAlignmentsAttr(), getAllocatePrivateIndicesAttr(),
4241 getPrivateVars(), getPrivateSymsAttr())))
4244 LogicalResult verifyDependVars =
4246 getDependIteratedKinds(), getDependIterated());
4247 if (
failed(verifyDependVars))
4248 return verifyDependVars;
4254 getInReductionVars(), getInReductionByref());
4267 auto iface = dyn_cast<BlockArgOpenMPOpInterface>(op);
4268 auto reductionVars = iface.getInReductionVars();
4283 if (!reductionVars.empty()) {
4289void TaskOp::getEffects(
4295 bool hasUnknownRecipeEffects =
4296 (!getPrivateVars().empty() && !getPrivateAssumeBoundedRecipeEffects()) ||
4297 (!getInReductionVars().empty() &&
4298 !getInReductionAssumeBoundedRecipeEffects());
4300 if (hasUnknownRecipeEffects) {
4313 const TaskgroupOperands &clauses) {
4315 TaskgroupOp::build(builder, state, clauses.allocateVars,
4316 clauses.allocatorVars,
4319 clauses.taskReductionVars,
4325LogicalResult TaskgroupOp::verify() {
4327 getOperation(), getAllocateVars(), getAllocatorVars(),
4328 getAllocateAlignmentsAttr(), getAllocatePrivateIndicesAttr())))
4332 getTaskReductionVars(),
4333 getTaskReductionByref());
4338 auto iface = dyn_cast<BlockArgOpenMPOpInterface>(op);
4339 auto taskVars = iface.getTaskReductionVars();
4340 for (
auto &source :
MutableArrayRef(taskVars.getBase(), taskVars.size())) {
4345 for (
BlockArgument arg : iface.getTaskReductionBlockArgs()) {
4353 if (!taskVars.empty()) {
4359void TaskgroupOp::getEffects(
4364 if (!getTaskReductionVars().empty() &&
4365 !getTaskReductionAssumeBoundedRecipeEffects())
4376 const TaskloopContextOperands &clauses) {
4378 TaskloopContextOp::build(
4379 builder, state, clauses.allocateVars, clauses.allocatorVars,
4382 clauses.grainsizeMod, clauses.grainsize, clauses.ifExpr,
4383 clauses.inReductionVars,
4385 makeArrayAttr(ctx, clauses.inReductionSyms), clauses.mergeable,
4386 clauses.nogroup, clauses.numTasksMod, clauses.numTasks, clauses.priority,
4387 clauses.privateVars,
4389 clauses.privateNeedsBarrier,
makeArrayAttr(ctx, clauses.reductionMods),
4390 clauses.reductionVars,
4392 makeArrayAttr(ctx, clauses.reductionSyms), clauses.threadset,
4394 state.
addAttribute(
"omp.combined", UnitAttr::get(ctx));
4397TaskloopWrapperOp TaskloopContextOp::getLoopOp() {
4398 return cast<TaskloopWrapperOp>(
4400 return isa<TaskloopWrapperOp>(op);
4404LogicalResult TaskloopContextOp::verify() {
4408 getOperation(), getAllocateVars(), getAllocatorVars(),
4409 getAllocateAlignmentsAttr(), getAllocatePrivateIndicesAttr(),
4410 getPrivateVars(), getPrivateSymsAttr())))
4414 getReductionVars(), getReductionByref(),
4415 getReductionModsAttr())) ||
4417 getInReductionVars(),
4418 getInReductionByref())))
4421 if (!getReductionVars().empty() && getNogroup())
4422 return emitError(
"if a reduction clause is present on the taskloop "
4423 "directive, the nogroup clause must not be specified");
4424 for (
auto var : getReductionVars()) {
4425 if (llvm::is_contained(getInReductionVars(), var))
4426 return emitError(
"the same list item cannot appear in both a reduction "
4427 "and an in_reduction clause");
4430 if (getGrainsize() && getNumTasks()) {
4432 "the grainsize clause and num_tasks clause are mutually exclusive and "
4433 "may not appear on the same taskloop directive");
4441 return emitOpError(
"must always contain the 'omp.combined' attribute");
4446LogicalResult TaskloopContextOp::verifyRegions() {
4447 Region ®ion = getRegion();
4449 return isa<TaskloopWrapperOp>(op);
4451 if (loopWrapperIt == region.
front().
end())
4452 return emitOpError()
4453 <<
"expected a TaskloopWrapperOp directly nested in the region";
4455 auto loopWrapperOp = cast<TaskloopWrapperOp>(*loopWrapperIt);
4456 auto loopNestOp = dyn_cast<LoopNestOp>(loopWrapperOp.getWrappedLoop());
4462 std::function<
bool(
Value)> isValidBoundValue = [&](
Value value) ->
bool {
4463 Region *valueRegion = value.getParentRegion();
4469 Operation *defOp = value.getDefiningOp();
4473 return llvm::all_of(defOp->
getOperands(), isValidBoundValue);
4475 auto hasUnsupportedTaskloopLocalBound = [&](
OperandRange range) ->
bool {
4476 return llvm::any_of(range,
4477 [&](
Value value) {
return !isValidBoundValue(value); });
4480 if (hasUnsupportedTaskloopLocalBound(loopNestOp.getLoopLowerBounds()) ||
4481 hasUnsupportedTaskloopLocalBound(loopNestOp.getLoopUpperBounds()) ||
4482 hasUnsupportedTaskloopLocalBound(loopNestOp.getLoopSteps())) {
4483 return emitOpError()
4484 <<
"expects loop bounds and steps to be defined outside of the "
4485 "taskloop.context region or by pure, regionless operations "
4486 "that do not depend on block arguments";
4497 const TaskloopWrapperOperands &clauses) {
4498 TaskloopWrapperOp::build(builder, state);
4501TaskloopContextOp TaskloopWrapperOp::getTaskloopContext() {
4502 return dyn_cast<TaskloopContextOp>(getOperation()->getParentOp());
4505LogicalResult TaskloopWrapperOp::verify() {
4506 TaskloopContextOp context = getTaskloopContext();
4508 return emitOpError() <<
"expected to be nested in a taskloop context op";
4512LogicalResult TaskloopWrapperOp::verifyRegions() {
4513 if (LoopWrapperInterface nested = getNestedWrapper()) {
4516 <<
"'omp.composite' attribute missing from composite wrapper";
4520 if (!isa<SimdOp>(nested))
4521 return emitError() <<
"only supported nested wrapper is 'omp.simd'";
4522 }
else if (isComposite()) {
4524 <<
"'omp.composite' attribute present in non-composite wrapper";
4548 for (
auto &iv : ivs)
4549 iv.type = loopVarType;
4554 result.addAttribute(
"loop_inclusive", UnitAttr::get(ctx));
4570 "collapse_num_loops",
4575 auto parseTiles = [&]() -> ParseResult {
4579 tiles.push_back(
tile);
4588 if (tiles.size() > 0)
4607 Region ®ion = getRegion();
4609 p <<
" (" << args <<
") : " << args[0].getType() <<
" = ("
4610 << getLoopLowerBounds() <<
") to (" << getLoopUpperBounds() <<
") ";
4611 if (getLoopInclusive())
4613 p <<
"step (" << getLoopSteps() <<
") ";
4614 if (
int64_t numCollapse = getCollapseNumLoops())
4615 if (numCollapse > 1)
4616 p <<
"collapse(" << numCollapse <<
") ";
4619 p <<
"tiles(" << tiles.value() <<
") ";
4625 const LoopNestOperands &clauses) {
4627 LoopNestOp::build(builder, state, clauses.collapseNumLoops,
4628 clauses.loopLowerBounds, clauses.loopUpperBounds,
4629 clauses.loopSteps, clauses.loopInclusive,
4633LogicalResult LoopNestOp::verify() {
4634 if (getLoopLowerBounds().empty())
4635 return emitOpError() <<
"must represent at least one loop";
4637 if (getLoopLowerBounds().size() != getIVs().size())
4638 return emitOpError() <<
"number of range arguments and IVs do not match";
4640 for (
auto [lb, iv] : llvm::zip_equal(getLoopLowerBounds(), getIVs())) {
4641 if (lb.getType() != iv.getType())
4642 return emitOpError()
4643 <<
"range argument type does not match corresponding IV type";
4646 uint64_t numIVs = getIVs().size();
4648 if (
const auto &numCollapse = getCollapseNumLoops())
4649 if (numCollapse > numIVs)
4650 return emitOpError()
4651 <<
"collapse value is larger than the number of loops";
4654 if (tiles.value().size() > numIVs)
4655 return emitOpError() <<
"too few canonical loops for tile dimensions";
4657 if (!llvm::dyn_cast_if_present<LoopWrapperInterface>((*this)->getParentOp()))
4658 return emitOpError() <<
"expects parent op to be a loop wrapper";
4663void LoopNestOp::gatherWrappers(
4666 while (
auto wrapper =
4667 llvm::dyn_cast_if_present<LoopWrapperInterface>(parent)) {
4668 wrappers.push_back(wrapper);
4677std::tuple<NewCliOp, OpOperand *, OpOperand *>
4683 return {{},
nullptr,
nullptr};
4686 "Unexpected type of cli");
4692 auto op = cast<LoopTransformationInterface>(use.getOwner());
4694 unsigned opnum = use.getOperandNumber();
4695 if (op.isGeneratee(opnum)) {
4696 assert(!gen &&
"Each CLI may have at most one def");
4698 }
else if (op.isApplyee(opnum)) {
4699 assert(!cons &&
"Each CLI may have at most one consumer");
4702 llvm_unreachable(
"Unexpected operand for a CLI");
4706 return {create, gen, cons};
4712 case llvm::omp::ProcBindKind::OMP_PROC_BIND_close:
4713 return ClauseProcBindKind::Close;
4714 case llvm::omp::ProcBindKind::OMP_PROC_BIND_master:
4715 return ClauseProcBindKind::Master;
4716 case llvm::omp::ProcBindKind::OMP_PROC_BIND_primary:
4717 return ClauseProcBindKind::Primary;
4718 case llvm::omp::ProcBindKind::OMP_PROC_BIND_spread:
4719 return ClauseProcBindKind::Spread;
4720 case llvm::omp::ProcBindKind::OMP_PROC_BIND_default:
4721 case llvm::omp::ProcBindKind::OMP_PROC_BIND_unknown:
4724 llvm_unreachable(
"unexpected proc-bind kind");
4747 std::string cliName{
"cli"};
4751 .Case([&](CanonicalLoopOp op) {
4754 .Case([&](UnrollHeuristicOp op) -> std::string {
4755 llvm_unreachable(
"heuristic unrolling does not generate a loop");
4757 .Case([&](FuseOp op) -> std::string {
4758 unsigned opnum =
generator->getOperandNumber();
4761 if (op.getFirst().has_value() && opnum != op.getFirst().value())
4762 return "canonloop_fuse";
4766 .Case([&](TileOp op) -> std::string {
4767 auto [generateesFirst, generateesCount] =
4768 op.getGenerateesODSOperandIndexAndLength();
4769 unsigned firstGrid = generateesFirst;
4770 unsigned firstIntratile = generateesFirst + generateesCount / 2;
4771 unsigned end = generateesFirst + generateesCount;
4772 unsigned opnum =
generator->getOperandNumber();
4774 if (firstGrid <= opnum && opnum < firstIntratile) {
4775 unsigned gridnum = opnum - firstGrid + 1;
4776 return (
"grid" + Twine(gridnum)).str();
4778 if (firstIntratile <= opnum && opnum < end) {
4779 unsigned intratilenum = opnum - firstIntratile + 1;
4780 return (
"intratile" + Twine(intratilenum)).str();
4782 llvm_unreachable(
"Unexpected generatee argument");
4784 .DefaultUnreachable(
"TODO: Custom name for this operation");
4787 setNameFn(
result, cliName);
4790LogicalResult NewCliOp::verify() {
4791 Value cli = getResult();
4794 "Unexpected type of cli");
4800 auto op = dyn_cast<mlir::omp::LoopTransformationInterface>(use.getOwner());
4803 emitOpError(
"CLI must only be used by loop transformations");
4808 unsigned opnum = use.getOperandNumber();
4809 if (op.isGeneratee(opnum)) {
4812 emitOpError(
"CLI must have at most one generator");
4814 .
append(
"first generator here:");
4816 .
append(
"second generator here:");
4821 }
else if (op.isApplyee(opnum)) {
4824 emitOpError(
"CLI must have at most one consumer");
4826 .
append(
"first consumer here:")
4830 .
append(
"second consumer here:")
4837 llvm_unreachable(
"Unexpected operand for a CLI");
4845 .
append(
"see consumer here: ")
4868 setNameFn(&getRegion().front(),
"body_entry");
4871void CanonicalLoopOp::getAsmBlockArgumentNames(
Region ®ion,
4879 p <<
'(' << getCli() <<
')';
4880 p <<
' ' << getInductionVar() <<
" : " << getInductionVar().getType()
4881 <<
" in range(" << getTripCount() <<
") ";
4891 CanonicalLoopInfoType cliType =
4892 CanonicalLoopInfoType::get(parser.
getContext());
4917 if (parser.
parseRegion(*region, {inductionVariable}))
4922 result.operands.append(cliOperand);
4928 return mlir::success();
4931LogicalResult CanonicalLoopOp::verify() {
4934 if (!getRegion().empty()) {
4935 Region ®ion = getRegion();
4938 "Canonical loop region must have exactly one argument");
4942 "Region argument must be the same type as the trip count");
4948Value CanonicalLoopOp::getInductionVar() {
return getRegion().getArgument(0); }
4950std::pair<unsigned, unsigned>
4951CanonicalLoopOp::getApplyeesODSOperandIndexAndLength() {
4956std::pair<unsigned, unsigned>
4957CanonicalLoopOp::getGenerateesODSOperandIndexAndLength() {
4958 return getODSOperandIndexAndLength(odsIndex_cli);
4972 p <<
'(' << getApplyee() <<
')';
4979 auto cliType = CanonicalLoopInfoType::get(parser.
getContext());
5002 return mlir::success();
5005std::pair<unsigned, unsigned>
5006UnrollHeuristicOp ::getApplyeesODSOperandIndexAndLength() {
5007 return getODSOperandIndexAndLength(odsIndex_applyee);
5010std::pair<unsigned, unsigned>
5011UnrollHeuristicOp::getGenerateesODSOperandIndexAndLength() {
5025 p <<
'(' << getApplyee() <<
')';
5032 auto cliType = CanonicalLoopInfoType::get(parser.
getContext());
5055 return mlir::success();
5058std::pair<unsigned, unsigned>
5059UnrollFullOp::getApplyeesODSOperandIndexAndLength() {
5060 return getODSOperandIndexAndLength(odsIndex_applyee);
5063std::pair<unsigned, unsigned>
5064UnrollFullOp::getGenerateesODSOperandIndexAndLength() {
5068LogicalResult UnrollFullOp::verify() {
5069 auto [create, gen, cons] =
decodeCli(getApplyee());
5071 return emitOpError() <<
"applyee CLI has no generator";
5075 if (
auto loop = dyn_cast<CanonicalLoopOp>(gen->getOwner())) {
5077 return emitOpError() <<
"applyee loop must have a constant trip count";
5089 uint64_t unrollFactor) {
5096 p <<
'(' << getApplyee() <<
')';
5099 attrs.emplace_back(getUnrollFactorAttrName(), getUnrollFactorAttr());
5106 auto cliType = CanonicalLoopInfoType::get(parser.
getContext());
5123 return mlir::success();
5126std::pair<unsigned, unsigned>
5127UnrollPartialOp::getApplyeesODSOperandIndexAndLength() {
5128 return getODSOperandIndexAndLength(odsIndex_applyee);
5131std::pair<unsigned, unsigned>
5132UnrollPartialOp::getGenerateesODSOperandIndexAndLength() {
5143 if (!generatees.empty())
5144 p <<
'(' << llvm::interleaved(generatees) <<
')';
5146 if (!applyees.empty())
5147 p <<
" <- (" << llvm::interleaved(applyees) <<
')';
5189 bool isOnlyCanonLoops =
true;
5191 for (
Value applyee : op.getApplyees()) {
5192 auto [create, gen, cons] =
decodeCli(applyee);
5195 return op.emitOpError() <<
"applyee CLI has no generator";
5197 auto loop = dyn_cast_or_null<CanonicalLoopOp>(gen->getOwner());
5198 canonLoops.push_back(loop);
5200 isOnlyCanonLoops =
false;
5205 if (!isOnlyCanonLoops)
5209 for (
auto i : llvm::seq<int>(1, canonLoops.size())) {
5210 auto parentLoop = canonLoops[i - 1];
5211 auto loop = canonLoops[i];
5213 if (parentLoop.getOperation() != loop.getOperation()->getParentOp())
5214 return op.emitOpError()
5215 <<
"tiled loop nest must be nested within each other";
5217 parentIVs.insert(parentLoop.getInductionVar());
5222 bool isPerfectlyNested = [&]() {
5223 auto &parentBody = parentLoop.getRegion();
5224 if (!parentBody.hasOneBlock())
5226 auto &parentBlock = parentBody.getBlocks().
front();
5228 auto nestedLoopIt = parentBlock.
begin();
5229 if (nestedLoopIt == parentBlock.
end() ||
5230 (&*nestedLoopIt != loop.getOperation()))
5233 auto termIt = std::next(nestedLoopIt);
5234 if (termIt == parentBlock.
end() || !isa<TerminatorOp>(termIt))
5237 if (std::next(termIt) != parentBlock.
end())
5242 if (!isPerfectlyNested)
5243 return op.emitOpError() <<
"tiled loop nest must be perfectly nested";
5245 if (parentIVs.contains(loop.getTripCount()))
5246 return op.emitOpError() <<
"tiled loop nest must be rectangular";
5263LogicalResult TileOp::verify() {
5264 if (getApplyees().empty())
5265 return emitOpError() <<
"must apply to at least one loop";
5267 if (getSizes().size() != getApplyees().size())
5268 return emitOpError() <<
"there must be one tile size for each applyee";
5270 if (!getGeneratees().empty() &&
5271 2 * getSizes().size() != getGeneratees().size())
5272 return emitOpError()
5273 <<
"expecting two times the number of generatees than applyees";
5278std::pair<unsigned, unsigned> TileOp ::getApplyeesODSOperandIndexAndLength() {
5279 return getODSOperandIndexAndLength(odsIndex_applyees);
5282std::pair<unsigned, unsigned> TileOp::getGenerateesODSOperandIndexAndLength() {
5283 return getODSOperandIndexAndLength(odsIndex_generatees);
5293 if (!generatees.empty())
5294 p <<
'(' << llvm::interleaved(generatees) <<
')';
5296 if (!applyees.empty())
5297 p <<
" <- (" << llvm::interleaved(applyees) <<
')';
5300LogicalResult FuseOp::verify() {
5301 if (getApplyees().size() < 2)
5302 return emitOpError() <<
"must apply to at least two loops";
5304 if (getFirst().has_value() && getCount().has_value()) {
5305 int64_t first = getFirst().value();
5306 int64_t count = getCount().value();
5307 if ((
unsigned)(first + count - 1) > getApplyees().size())
5308 return emitOpError() <<
"the numbers of applyees must be at least first "
5309 "minus one plus count attributes";
5310 if (!getGeneratees().empty() &&
5311 getGeneratees().size() != getApplyees().size() + 1 - count)
5312 return emitOpError() <<
"the number of generatees must be the number of "
5313 "aplyees plus one minus count";
5316 if (!getGeneratees().empty() && getGeneratees().size() != 1)
5317 return emitOpError()
5318 <<
"in a complete fuse the number of generatees must be exactly 1";
5320 for (
auto &&applyee : getApplyees()) {
5321 auto [create, gen, cons] =
decodeCli(applyee);
5324 return emitOpError() <<
"applyee CLI has no generator";
5325 auto loop = dyn_cast_or_null<CanonicalLoopOp>(gen->getOwner());
5327 return emitOpError()
5328 <<
"currently only supports omp.canonical_loop as applyee";
5332std::pair<unsigned, unsigned> FuseOp::getApplyeesODSOperandIndexAndLength() {
5333 return getODSOperandIndexAndLength(odsIndex_applyees);
5336std::pair<unsigned, unsigned> FuseOp::getGenerateesODSOperandIndexAndLength() {
5337 return getODSOperandIndexAndLength(odsIndex_generatees);
5345 const CriticalDeclareOperands &clauses) {
5346 CriticalDeclareOp::build(builder, state, clauses.symName,
5347 clauses.symVisibility, clauses.hint);
5350LogicalResult CriticalDeclareOp::verify() {
5357 assert(bodyBuilder &&
"expected a body builder callback");
5358 build(builder, state, name);
5361 bodyBuilder(builder, state.
location);
5364LogicalResult CriticalOp::verify() {
5365 SymbolRefAttr currentName = getNameAttr();
5367 CriticalOp parentCritical = (*this)->getParentOfType<CriticalOp>();
5369 while (parentCritical) {
5370 SymbolRefAttr parentName = parentCritical.getNameAttr();
5372 if (currentName == parentName) {
5374 return emitOpError() <<
"cannot be nested inside another omp.critical "
5375 "region with the same name ("
5376 << currentName <<
")";
5378 return emitOpError() <<
"cannot be nested inside another unnamed "
5379 "omp.critical region";
5383 parentCritical = parentCritical->getParentOfType<CriticalOp>();
5390 if (getNameAttr()) {
5391 SymbolRefAttr symbolRef = getNameAttr();
5395 return emitOpError() <<
"expected symbol reference " << symbolRef
5396 <<
" to point to a critical declaration";
5407LogicalResult ErrorOp::verify() {
5408 if (getMessage() && getMessageExpr())
5409 return emitOpError() <<
"the message must be provided either as a constant "
5410 "`message` attribute or as a `message_expr` "
5411 "operand, but not both";
5428 return op.
emitOpError() <<
"must be nested inside of a loop";
5432 if (
auto wsloopOp = dyn_cast<WsloopOp>(wrapper)) {
5433 IntegerAttr orderedAttr = wsloopOp.getOrderedAttr();
5435 return op.
emitOpError() <<
"the enclosing worksharing-loop region must "
5436 "have an ordered clause";
5438 if (hasRegion && orderedAttr.getInt() != 0)
5439 return op.
emitOpError() <<
"the enclosing loop's ordered clause must not "
5440 "have a parameter present";
5442 if (!hasRegion && orderedAttr.getInt() == 0)
5443 return op.
emitOpError() <<
"the enclosing loop's ordered clause must "
5444 "have a parameter present";
5445 }
else if (!isa<SimdOp>(wrapper)) {
5446 return op.
emitOpError() <<
"must be nested inside of a worksharing, simd "
5447 "or worksharing simd loop";
5453 const OrderedOperands &clauses) {
5454 OrderedOp::build(builder, state, clauses.doacrossDependType,
5455 clauses.doacrossNumLoops, clauses.doacrossDependVars);
5458LogicalResult OrderedOp::verify() {
5462 auto wrapper = (*this)->getParentOfType<WsloopOp>();
5463 if (!wrapper || *wrapper.getOrdered() != *getDoacrossNumLoops())
5464 return emitOpError() <<
"number of variables in depend clause does not "
5465 <<
"match number of iteration variables in the "
5472 const OrderedRegionOperands &clauses) {
5473 OrderedRegionOp::build(builder, state, clauses.parLevelSimd);
5483 const TaskwaitOperands &clauses) {
5499LogicalResult AtomicReadOp::verify() {
5500 if (verifyCommon().
failed())
5501 return mlir::failure();
5504 if (
auto moduleOp = getOperation()->getParentOfType<ModuleOp>())
5505 if (
Attribute verAttr = moduleOp->getDiscardableAttr(
"omp.version"))
5506 version = llvm::cast<VersionAttr>(verAttr).getVersion();
5508 if (
auto mo = getMemoryOrder()) {
5509 if (*mo == ClauseMemoryOrderKind::Release) {
5510 return emitError(
"memory-order must not be release for atomic reads");
5512 if (*mo == ClauseMemoryOrderKind::Acq_rel) {
5515 return emitError(
"memory-order must not be acq_rel for atomic reads");
5525LogicalResult AtomicWriteOp::verify() {
5526 if (verifyCommon().
failed())
5527 return mlir::failure();
5530 if (
auto moduleOp = getOperation()->getParentOfType<ModuleOp>())
5531 if (
Attribute verAttr = moduleOp->getDiscardableAttr(
"omp.version"))
5532 version = llvm::cast<VersionAttr>(verAttr).getVersion();
5534 if (
auto mo = getMemoryOrder()) {
5535 if (*mo == ClauseMemoryOrderKind::Acquire) {
5536 return emitError(
"memory-order must not be acquire for atomic writes");
5538 if (*mo == ClauseMemoryOrderKind::Acq_rel) {
5541 return emitError(
"memory-order must not be acq_rel for atomic writes");
5551LogicalResult AtomicUpdateOp::canonicalize(AtomicUpdateOp op,
5557 if (
Value writeVal = op.getWriteOpVal()) {
5559 op, op.getX(), writeVal, op.getHintAttr(), op.getMemoryOrderAttr());
5565LogicalResult AtomicUpdateOp::verify() {
5566 if (verifyCommon().
failed())
5567 return mlir::failure();
5570 if (
auto moduleOp = getOperation()->getParentOfType<ModuleOp>())
5571 if (
Attribute verAttr = moduleOp->getDiscardableAttr(
"omp.version"))
5572 version = llvm::cast<VersionAttr>(verAttr).getVersion();
5574 if (
auto mo = getMemoryOrder()) {
5575 if (*mo == ClauseMemoryOrderKind::Acq_rel ||
5576 *mo == ClauseMemoryOrderKind::Acquire) {
5580 "memory-order must not be acq_rel or acquire for atomic updates");
5587LogicalResult AtomicUpdateOp::verifyRegions() {
return verifyRegionsCommon(); }
5593AtomicReadOp AtomicCaptureOp::getAtomicReadOp() {
5594 if (
auto op = dyn_cast<AtomicReadOp>(getFirstOp()))
5596 return dyn_cast<AtomicReadOp>(getSecondOp());
5599AtomicWriteOp AtomicCaptureOp::getAtomicWriteOp() {
5600 if (
auto op = dyn_cast<AtomicWriteOp>(getFirstOp()))
5602 return dyn_cast<AtomicWriteOp>(getSecondOp());
5605AtomicUpdateOp AtomicCaptureOp::getAtomicUpdateOp() {
5606 if (
auto op = dyn_cast<AtomicUpdateOp>(getFirstOp()))
5608 return dyn_cast<AtomicUpdateOp>(getSecondOp());
5611AtomicCompareOp AtomicCaptureOp::getAtomicCompareOp() {
5612 if (
auto op = dyn_cast<AtomicCompareOp>(getFirstOp()))
5614 return dyn_cast<AtomicCompareOp>(getSecondOp());
5617LogicalResult AtomicCaptureOp::verify() {
5621LogicalResult AtomicCaptureOp::verifyRegions() {
5622 if (verifyRegionsCommon().
failed())
5623 return mlir::failure();
5625 if (getFirstOp()->getInherentAttr(
"hint").value_or(
Attribute{}) ||
5626 getSecondOp()->getInherentAttr(
"hint").value_or(
Attribute{}))
5628 "operations inside capture region must not have hint clause");
5630 if (getFirstOp()->getInherentAttr(
"memory_order").value_or(
Attribute{}) ||
5631 getSecondOp()->getInherentAttr(
"memory_order").value_or(
Attribute{}))
5633 "operations inside capture region must not have memory_order clause");
5641LogicalResult AtomicCompareOp::verify() {
5642 if (verifyCommon().
failed())
5643 return mlir::failure();
5647 if (
auto failOrder = getFailMemoryOrder()) {
5648 if (*failOrder != ClauseMemoryOrderKind::Seq_cst &&
5649 *failOrder != ClauseMemoryOrderKind::Acquire &&
5650 *failOrder != ClauseMemoryOrderKind::Relaxed)
5652 "fail_memory_order must be 'seq_cst', 'acquire' or 'relaxed'");
5657LogicalResult AtomicCompareOp::verifyRegions() {
5658 if (verifyRegionsCommon().
failed())
5659 return mlir::failure();
5661 if (verifyOperator().
failed())
5662 return mlir::failure();
5667 if (!terminator || !isa<YieldOp>(terminator))
5668 return emitOpError(
"region must be terminated with omp.yield");
5677void ThreadprivateOp::getEffects(
5684 cast<OpResult>(getTlsAddr()));
5695 const CancelOperands &clauses) {
5696 CancelOp::build(builder, state, clauses.cancelDirective, clauses.ifExpr);
5709LogicalResult CancelOp::verify() {
5710 ClauseCancellationConstructType cct = getCancelDirective();
5713 if (!structuralParent)
5714 return emitOpError() <<
"Orphaned cancel construct";
5716 if ((cct == ClauseCancellationConstructType::Parallel) &&
5717 !mlir::isa<ParallelOp>(structuralParent)) {
5718 return emitOpError() <<
"cancel parallel must appear "
5719 <<
"inside a parallel region";
5721 if (cct == ClauseCancellationConstructType::Loop) {
5724 auto wsloopOp = mlir::dyn_cast<WsloopOp>(structuralParent->
getParentOp());
5727 return emitOpError()
5728 <<
"cancel loop must appear inside a worksharing-loop region";
5730 if (wsloopOp.getNowaitAttr()) {
5731 return emitError() <<
"A worksharing construct that is canceled "
5732 <<
"must not have a nowait clause";
5734 if (wsloopOp.getOrderedAttr()) {
5735 return emitError() <<
"A worksharing construct that is canceled "
5736 <<
"must not have an ordered clause";
5739 }
else if (cct == ClauseCancellationConstructType::Sections) {
5743 mlir::dyn_cast<SectionsOp>(structuralParent->
getParentOp());
5745 return emitOpError() <<
"cancel sections must appear "
5746 <<
"inside a sections region";
5748 if (sectionsOp.getNowait()) {
5749 return emitError() <<
"A sections construct that is canceled "
5750 <<
"must not have a nowait clause";
5753 if ((cct == ClauseCancellationConstructType::Taskgroup) &&
5754 (!mlir::isa<omp::TaskOp>(structuralParent) &&
5755 !mlir::isa<omp::TaskloopWrapperOp>(structuralParent->
getParentOp()))) {
5756 return emitOpError() <<
"cancel taskgroup must appear "
5757 <<
"inside a task region";
5767 const CancellationPointOperands &clauses) {
5768 CancellationPointOp::build(builder, state, clauses.cancelDirective);
5771LogicalResult CancellationPointOp::verify() {
5772 ClauseCancellationConstructType cct = getCancelDirective();
5775 if (!structuralParent)
5776 return emitOpError() <<
"Orphaned cancellation point";
5778 if ((cct == ClauseCancellationConstructType::Parallel) &&
5779 !mlir::isa<ParallelOp>(structuralParent)) {
5780 return emitOpError() <<
"cancellation point parallel must appear "
5781 <<
"inside a parallel region";
5785 if ((cct == ClauseCancellationConstructType::Loop) &&
5786 !mlir::isa<WsloopOp>(structuralParent->
getParentOp())) {
5787 return emitOpError() <<
"cancellation point loop must appear "
5788 <<
"inside a worksharing-loop region";
5790 if ((cct == ClauseCancellationConstructType::Sections) &&
5791 !mlir::isa<omp::SectionOp>(structuralParent)) {
5792 return emitOpError() <<
"cancellation point sections must appear "
5793 <<
"inside a sections region";
5795 if ((cct == ClauseCancellationConstructType::Taskgroup) &&
5796 (!mlir::isa<omp::TaskOp>(structuralParent) &&
5797 !mlir::isa<omp::TaskloopWrapperOp>(structuralParent->
getParentOp()))) {
5798 return emitOpError() <<
"cancellation point taskgroup must appear "
5799 <<
"inside a task region";
5808LogicalResult MapBoundsOp::verify() {
5809 auto extent = getExtent();
5811 if (!extent && !upperbound)
5812 return emitError(
"expected extent or upperbound.");
5819 PrivateClauseOp::build(
5820 odsBuilder, odsState, symName,
nullptr, type,
5821 DataSharingClauseTypeAttr::get(odsBuilder.
getContext(),
5822 DataSharingClauseType::Private));
5825LogicalResult PrivateClauseOp::verifyRegions() {
5826 Type argType = getArgType();
5827 auto verifyTerminator = [&](
Operation *terminator,
bool yieldsValue,
5828 bool yieldsAnyType) -> LogicalResult {
5832 if (!llvm::isa<YieldOp>(terminator))
5834 <<
"expected exit block terminator to be an `omp.yield` op.";
5836 YieldOp yieldOp = llvm::cast<YieldOp>(terminator);
5837 TypeRange yieldedTypes = yieldOp.getResults().getTypes();
5840 if (yieldedTypes.empty())
5844 <<
"Did not expect any values to be yielded.";
5847 if (yieldedTypes.size() == 1 &&
5848 (yieldsAnyType || yieldedTypes.front() == argType))
5852 <<
"Invalid yielded value. Expected ";
5854 error <<
"a single value";
5856 error <<
"type: " << argType;
5859 if (yieldedTypes.empty())
5862 error << yieldedTypes;
5868 StringRef regionName,
bool yieldsValue,
5869 bool yieldsAnyType =
false) -> LogicalResult {
5870 assert(!region.
empty());
5874 <<
"`" << regionName <<
"`: " <<
"expected " << expectedNumArgs
5877 for (
Block &block : region) {
5891 for (
Region *region : getRegions())
5892 for (
Type ty : region->getArgumentTypes())
5894 return emitError() <<
"Region argument type mismatch: got " << ty
5895 <<
" expected " << argType <<
".";
5898 if (!initRegion.
empty() &&
5903 DataSharingClauseType dsType = getDataSharingType();
5905 if (dsType == DataSharingClauseType::Private && !getCopyRegion().empty())
5906 return emitError(
"`private` clauses do not require a `copy` region.");
5908 if (dsType == DataSharingClauseType::FirstPrivate && getCopyRegion().empty())
5910 "`firstprivate` clauses require at least a `copy` region.");
5912 if (dsType == DataSharingClauseType::FirstPrivate &&
5917 if (dsType == DataSharingClauseType::Linear && !getCopyRegion().empty())
5918 return emitError(
"`linear` clauses do not require a `copy` region.");
5920 if (!getDataAddressRegion().empty()) {
5921 if (dsType != DataSharingClauseType::Linear)
5923 "only `linear` clauses can have a `data_address` region.");
5925 "data_address",
true,
5930 if (!getDeallocRegion().empty() &&
5943 const MaskedOperands &clauses) {
5944 MaskedOp::build(builder, state, clauses.filteredThreadId);
5952 const DispatchOperands &clauses) {
5953 DispatchOp::build(builder, state, clauses.nocontext, clauses.novariants,
5962 const ScanOperands &clauses) {
5963 ScanOp::build(builder, state, clauses.inclusiveVars, clauses.exclusiveVars);
5966LogicalResult ScanOp::verify() {
5967 if (hasExclusiveVars() == hasInclusiveVars())
5969 "Exactly one of EXCLUSIVE or INCLUSIVE clause is expected");
5970 if (WsloopOp parentWsLoopOp = (*this)->getParentOfType<WsloopOp>()) {
5971 if (parentWsLoopOp.hasReductionModifier(ReductionModifier::inscan))
5974 if (SimdOp parentSimdOp = (*this)->getParentOfType<SimdOp>()) {
5975 if (parentSimdOp.hasReductionModifier(ReductionModifier::inscan))
5978 return emitError(
"SCAN directive needs to be enclosed within a parent "
5979 "worksharing loop construct or SIMD construct with INSCAN "
5980 "reduction modifier");
5985 std::optional<uint64_t> alignment) {
5986 if (alignment.has_value()) {
5987 if ((alignment.value() != 0) && !llvm::has_single_bit(alignment.value()))
5989 <<
"ALIGN value : " << alignment.value() <<
" must be power of 2";
5994LogicalResult AllocateDirOp::verify() {
6002LogicalResult AllocSharedMemOp::verify() {
6010LogicalResult FreeSharedMemOp::verify() {
6018LogicalResult WorkdistributeOp::verify() {
6020 return emitOpError() <<
"cannot be a non-innermost combined construct leaf";
6023 Region ®ion = getRegion();
6025 return emitOpError(
"region cannot be empty");
6028 if (entryBlock.
empty())
6029 return emitOpError(
"region must contain a structured block");
6031 bool hasTerminator =
false;
6032 for (
Block &block : region) {
6033 if (isa<TerminatorOp>(block.
back())) {
6034 if (hasTerminator) {
6035 return emitOpError(
"region must have exactly one terminator");
6037 hasTerminator =
true;
6040 if (!hasTerminator) {
6041 return emitOpError(
"region must be terminated with omp.terminator");
6045 if (isa<BarrierOp>(op)) {
6047 "explicit barriers are not allowed in workdistribute region");
6050 if (isa<ParallelOp>(op)) {
6052 "nested parallel constructs not allowed in workdistribute");
6054 if (isa<TeamsOp>(op)) {
6056 "nested teams constructs not allowed in workdistribute");
6060 if (walkResult.wasInterrupted())
6064 if (!llvm::dyn_cast<TeamsOp>(parentOp))
6065 return emitOpError(
"workdistribute must be nested under teams");
6073LogicalResult DeclareSimdOp::verify() {
6076 dyn_cast_if_present<mlir::FunctionOpInterface>((*this)->getParentOp());
6078 return emitOpError() <<
"must be nested inside a function";
6080 if (getInbranch() && getNotinbranch())
6081 return emitOpError(
"cannot have both 'inbranch' and 'notinbranch'");
6087 if (getLinearSyms())
6088 return emitOpError(
"linear privatizers are not allowed");
6094 const DeclareSimdOperands &clauses) {
6096 DeclareSimdOp::build(
6097 odsBuilder, odsState, clauses.alignedVars,
6099 clauses.linearVars, clauses.linearStepVars, clauses.linearVarTypes,
6100 clauses.linearModifiers,
makeArrayAttr(ctx, clauses.linearSyms),
6101 clauses.notinbranch, clauses.simdlen, clauses.uniformVars);
6118 return mlir::failure();
6119 return mlir::success();
6126 for (
unsigned i = 0; i < uniformVars.size(); ++i) {
6129 p << uniformVars[i] <<
" : " << uniformTypes[i];
6144 parser, iterated, iteratedTypes, affinityVars, affinityVarTypes,
6145 [&]() -> ParseResult {
return success(); })))
6179 OpAsmParser::Argument &arg = ivArgs.emplace_back();
6180 if (parser.parseArgument(arg))
6184 if (succeeded(parser.parseOptionalColon())) {
6185 if (parser.parseType(arg.type))
6188 arg.type = parser.getBuilder().getIndexType();
6200 OpAsmParser::UnresolvedOperand lb, ub, st;
6201 if (parser.parseOperand(lb) || parser.parseKeyword(
"to") ||
6202 parser.parseOperand(ub) || parser.parseKeyword(
"step") ||
6203 parser.parseOperand(st))
6208 steps.push_back(st);
6216 if (ivArgs.size() != lbs.size())
6218 <<
"mismatch: " << ivArgs.size() <<
" variables but " << lbs.size()
6221 for (
auto &arg : ivArgs) {
6222 lbTypes.push_back(arg.type);
6223 ubTypes.push_back(arg.type);
6224 stepTypes.push_back(arg.type);
6244 for (
unsigned i = 0, e = lbs.size(); i < e; ++i) {
6247 p << lbs[i] <<
" to " << ubs[i] <<
" step " << steps[i];
6255YieldOp IteratorOp::getYieldOp() {
6257 for (
Block &block : getRegion()) {
6259 dyn_cast_if_present<YieldOp>(block.
empty() ?
nullptr : &block.
back());
6269LogicalResult IteratorOp::verify() {
6270 auto iteratedTy = llvm::dyn_cast<omp::IteratedType>(getIterated().
getType());
6272 return emitOpError() <<
"result must be omp.iterated<entry_ty>";
6275 if (getLoopLowerBounds().size() != ivs.size())
6276 return emitOpError() <<
"number of range arguments and IVs do not match";
6278 for (
auto [lb, iv] : llvm::zip_equal(getLoopLowerBounds(), ivs)) {
6279 if (lb.getType() != iv.getType())
6280 return emitOpError()
6281 <<
"range argument type does not match corresponding IV type";
6284 for (
Value step : getLoopSteps()) {
6286 return emitOpError() <<
"loop step must not be zero";
6289 YieldOp yield = getYieldOp();
6291 bool hasYield = llvm::any_of(getRegion(), [](
Block &block) {
6292 return !block.
empty() && isa<YieldOp>(block.
back());
6295 return emitOpError() <<
"region must contain exactly one omp.yield";
6296 return emitOpError() <<
"region must be terminated by omp.yield";
6299 if (yield.getNumOperands() != 1)
6300 return emitOpError()
6301 <<
"omp.yield in omp.iterator region must yield exactly one value";
6303 mlir::Type yieldedTy = yield.getOperand(0).getType();
6304 mlir::Type elemTy = iteratedTy.getElementType();
6306 if (yieldedTy != elemTy)
6307 return emitOpError() <<
"omp.iterated element type (" << elemTy
6308 <<
") does not match omp.yield operand type ("
6309 << yieldedTy <<
")";
6314LogicalResult IteratorOp::verifyRegions() {
6316 for (
Block &block : getRegion()) {
6320 <<
"expected exit block terminator to be an `omp.yield` op.";
6333 return emitOpError() <<
"expected symbol reference '" << getSymName()
6334 <<
"' to point to a global variable";
6336 if (isa<FunctionOpInterface>(symbol))
6337 return emitOpError() <<
"expected symbol reference '" << getSymName()
6338 <<
"' to point to a global variable, not a function";
6343#define GET_ATTRDEF_CLASSES
6344#include "mlir/Dialect/OpenMP/OpenMPOpsAttributes.cpp.inc"
6346#define GET_OP_CLASSES
6347#include "mlir/Dialect/OpenMP/OpenMPOps.cpp.inc"
6349#define GET_TYPEDEF_CLASSES
6350#include "mlir/Dialect/OpenMP/OpenMPOpsTypes.cpp.inc"
static std::optional< int64_t > getUpperBound(Value iv)
Gets the constant upper bound on an affine.for iv.
static LogicalResult verifyRegion(emitc::SwitchOp op, Region ®ion, const Twine &name)
static const mlir::GenInfo * generator
static LogicalResult verifyNontemporalClause(Operation *op, OperandRange nontemporalVars)
static DenseI64ArrayAttr makeDenseI64ArrayAttr(MLIRContext *ctx, const ArrayRef< int64_t > intArray)
static void printDependVarList(OpAsmPrinter &p, Operation *op, OperandRange dependVars, TypeRange dependTypes, std::optional< ArrayAttr > dependKinds, OperandRange iteratedVars, TypeRange iteratedTypes, std::optional< ArrayAttr > iteratedKinds)
Print Depend clause.
static ParseResult parseTargetOpRegion(OpAsmParser &parser, Region ®ion, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &hasDeviceAddrVars, SmallVectorImpl< Type > &hasDeviceAddrTypes, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &hostEvalVars, SmallVectorImpl< Type > &hostEvalTypes, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &mapVars, SmallVectorImpl< Type > &mapTypes, llvm::SmallVectorImpl< OpAsmParser::UnresolvedOperand > &privateVars, llvm::SmallVectorImpl< Type > &privateTypes, ArrayAttr &privateSyms, UnitAttr &privateNeedsBarrier, DenseI64ArrayAttr &privateMaps)
static constexpr StringRef getPrivateNeedsBarrierSpelling()
static void printHeapAllocClause(OpAsmPrinter &p, Operation *op, TypeAttr inType, ValueRange typeparams, TypeRange typeparamsTypes, ValueRange shape, TypeRange shapeTypes)
static ParseResult parseInReductionPrivateReductionRegion(OpAsmParser &parser, Region ®ion, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &inReductionVars, SmallVectorImpl< Type > &inReductionTypes, DenseBoolArrayAttr &inReductionByref, ArrayAttr &inReductionSyms, llvm::SmallVectorImpl< OpAsmParser::UnresolvedOperand > &privateVars, llvm::SmallVectorImpl< Type > &privateTypes, ArrayAttr &privateSyms, UnitAttr &privateNeedsBarrier, ArrayAttr &reductionMods, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &reductionVars, SmallVectorImpl< Type > &reductionTypes, DenseBoolArrayAttr &reductionByref, ArrayAttr &reductionSyms)
static ParseResult parseInReductionPrivateRegion(OpAsmParser &parser, Region ®ion, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &inReductionVars, SmallVectorImpl< Type > &inReductionTypes, DenseBoolArrayAttr &inReductionByref, ArrayAttr &inReductionSyms, llvm::SmallVectorImpl< OpAsmParser::UnresolvedOperand > &privateVars, llvm::SmallVectorImpl< Type > &privateTypes, ArrayAttr &privateSyms, UnitAttr &privateNeedsBarrier)
static ArrayAttr makeArrayAttr(MLIRContext *context, llvm::ArrayRef< Attribute > attrs)
static ParseResult parseClauseAttr(AsmParser &parser, ClauseAttr &attr)
static void printLinearPrivateReductionRegion(OpAsmPrinter &p, Operation *op, Region ®ion, ValueRange linearVars, TypeRange linearTypes, ValueRange linearStepVars, TypeRange linearStepTypes, ArrayAttr linearVarTypes, ArrayAttr linearModifiers, ArrayAttr linearSyms, ValueRange privateVars, TypeRange privateTypes, ArrayAttr privateSyms, UnitAttr privateNeedsBarrier, ArrayAttr reductionMods, ValueRange reductionVars, TypeRange reductionTypes, DenseBoolArrayAttr reductionByref, ArrayAttr reductionSyms)
static ParseResult parseLinearPrivateReductionRegion(OpAsmParser &parser, Region ®ion, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &linearVars, SmallVectorImpl< Type > &linearTypes, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &linearStepVars, SmallVectorImpl< Type > &linearStepTypes, ArrayAttr &linearVarTypes, ArrayAttr &linearModifiers, ArrayAttr &linearSyms, llvm::SmallVectorImpl< OpAsmParser::UnresolvedOperand > &privateVars, llvm::SmallVectorImpl< Type > &privateTypes, ArrayAttr &privateSyms, UnitAttr &privateNeedsBarrier, ArrayAttr &reductionMods, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &reductionVars, SmallVectorImpl< Type > &reductionTypes, DenseBoolArrayAttr &reductionByref, ArrayAttr &reductionSyms)
static void printDynGroupprivateClause(OpAsmPrinter &printer, Operation *op, AccessGroupModifierAttr modifierFirst, FallbackModifierAttr modifierSecond, Value dynGroupprivateSize, Type sizeType)
static void printAllocateAndAllocator(OpAsmPrinter &p, Operation *op, OperandRange allocateVars, TypeRange allocateTypes, OperandRange allocatorVars, TypeRange allocatorTypes)
Print allocate clause.
static DenseBoolArrayAttr makeDenseBoolArrayAttr(MLIRContext *ctx, const ArrayRef< bool > boolArray)
static std::string generateLoopNestingName(StringRef prefix, CanonicalLoopOp op)
Generate a name of a canonical loop nest of the format <prefix>(_r<idx>_s<idx>)*.
static ParseResult parseAffinityClause(OpAsmParser &parser, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &iterated, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &affinityVars, SmallVectorImpl< Type > &iteratedTypes, SmallVectorImpl< Type > &affinityVarTypes)
static void printSplitIteratedList(OpAsmPrinter &p, ValueRange iteratedVars, TypeRange iteratedTypes, ValueRange plainVars, TypeRange plainTypes, PrintPrefixFn &&printPrefixForPlain, PrintPrefixFn &&printPrefixForIterated)
static LogicalResult verifyDependVarList(Operation *op, std::optional< ArrayAttr > dependKinds, OperandRange dependVars, std::optional< ArrayAttr > iteratedKinds, OperandRange iteratedVars)
Verifies Depend clause.
static void addUnknownMemoryEffects(SmallVectorImpl< MemoryEffects::EffectInstance > &effects)
Add arbitrary read, write, allocate, and free effects.
static void printBlockArgClause(OpAsmPrinter &p, MLIRContext *ctx, StringRef clauseName, ValueRange argsSubrange, std::optional< MapPrintArgs > mapArgs)
static void printAffinityClause(OpAsmPrinter &p, Operation *op, ValueRange iterated, ValueRange affinityVars, TypeRange iteratedTypes, TypeRange affinityVarTypes)
static void printBlockArgRegion(OpAsmPrinter &p, Operation *op, Region ®ion, const AllRegionPrintArgs &args)
static ParseResult parseGranularityClause(OpAsmParser &parser, ClauseTypeAttr &prescriptiveness, std::optional< OpAsmParser::UnresolvedOperand > &operand, Type &operandType, std::optional< ClauseType >(*symbolizeClause)(StringRef), StringRef clauseName)
static void printIteratorHeader(OpAsmPrinter &p, Operation *op, Region ®ion, ValueRange lbs, ValueRange ubs, ValueRange steps, TypeRange, TypeRange, TypeRange)
static void getInReductionEffects(Operation *op, SmallVectorImpl< MemoryEffects::EffectInstance > &effects)
static LogicalResult verifyDeclareTargetAttr(Operation *op, Attribute attr)
static ParseResult parseHeapAllocClause(OpAsmParser &parser, TypeAttr &inTypeAttr, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &typeparams, SmallVectorImpl< Type > &typeparamsTypes, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &shape, SmallVectorImpl< Type > &shapeTypes)
operation ::= $in_type ( ( $typeparams ) )? ( , $shape )?
static void printInReductionClause(OpAsmPrinter &p, Operation *op, ValueRange inReductionVars, TypeRange inReductionTypes, DenseBoolArrayAttr inReductionByref, ArrayAttr inReductionSyms)
Prints an in_reduction clause for an operation that does not give its list items entry block argument...
static void printClauseWithRegionArgs(OpAsmPrinter &p, MLIRContext *ctx, StringRef clauseName, ValueRange argsSubrange, ValueRange operands, TypeRange types, ArrayAttr symbols=nullptr, DenseI64ArrayAttr mapIndices=nullptr, DenseBoolArrayAttr byref=nullptr, ArrayAttr modifier=nullptr, UnitAttr needsBarrier=nullptr)
static ParseResult parseIteratorHeader(OpAsmParser &parser, Region ®ion, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &lbs, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &ubs, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &steps, SmallVectorImpl< Type > &lbTypes, SmallVectorImpl< Type > &ubTypes, SmallVectorImpl< Type > &stepTypes)
static LogicalResult verifyReductionVarList(Operation *op, std::optional< ArrayAttr > reductionSyms, OperandRange reductionVars, std::optional< ArrayRef< bool > > reductionByref, ArrayAttr reductionMods=nullptr)
Verifies Reduction Clause.
static ParseResult parseBlockArgRegion(OpAsmParser &parser, Region ®ion, AllRegionParseArgs args)
static ParseResult parseLoopTransformClis(OpAsmParser &parser, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &generateesOperands, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &applyeesOperands)
static ParseResult parseSynchronizationHint(OpAsmParser &parser, IntegerAttr &hintAttr)
Parses a Synchronization Hint clause.
static void printLinearClause(OpAsmPrinter &p, Operation *op, ValueRange linearVars, TypeRange linearTypes, ValueRange linearStepVars, TypeRange stepVarTypes, ArrayAttr linearModifiers, ArrayAttr linearSyms)
Print Linear Clause.
static void printScheduleClause(OpAsmPrinter &p, Operation *op, ClauseScheduleKindAttr scheduleKind, ScheduleModifierAttr scheduleMod, UnitAttr scheduleSimd, Value scheduleChunk, Type scheduleChunkType)
Print schedule clause.
static ParseResult parsePrivateReductionRegion(OpAsmParser &parser, Region ®ion, llvm::SmallVectorImpl< OpAsmParser::UnresolvedOperand > &privateVars, llvm::SmallVectorImpl< Type > &privateTypes, ArrayAttr &privateSyms, UnitAttr &privateNeedsBarrier, ArrayAttr &reductionMods, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &reductionVars, SmallVectorImpl< Type > &reductionTypes, DenseBoolArrayAttr &reductionByref, ArrayAttr &reductionSyms)
static void printCopyprivate(OpAsmPrinter &p, Operation *op, OperandRange copyprivateVars, TypeRange copyprivateTypes, std::optional< ArrayAttr > copyprivateSyms)
Print Copyprivate clause.
static ParseResult parseOrderClause(OpAsmParser &parser, ClauseOrderKindAttr &order, OrderModifierAttr &orderMod)
static bool mapTypeToBool(ClauseMapFlags value, ClauseMapFlags flag)
static void printAlignedClause(OpAsmPrinter &p, Operation *op, ValueRange alignedVars, TypeRange alignedTypes, std::optional< ArrayAttr > alignments)
Print Aligned Clause.
static bool targetInReductionCapturedBy(Value inReductionVar, Value mapVarPtr)
An omp.target in_reduction operand is captured by a map_entries entry when the entry's MapInfoOp var_...
static LogicalResult verifySynchronizationHint(Operation *op, uint64_t hint)
Verifies a synchronization hint clause.
static ParseResult parseUseDeviceAddrUseDevicePtrRegion(OpAsmParser &parser, Region ®ion, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &useDeviceAddrVars, SmallVectorImpl< Type > &useDeviceAddrTypes, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &useDevicePtrVars, SmallVectorImpl< Type > &useDevicePtrTypes)
static void printPrivateReductionRegion(OpAsmPrinter &p, Operation *op, Region ®ion, ValueRange privateVars, TypeRange privateTypes, ArrayAttr privateSyms, UnitAttr privateNeedsBarrier, ArrayAttr reductionMods, ValueRange reductionVars, TypeRange reductionTypes, DenseBoolArrayAttr reductionByref, ArrayAttr reductionSyms)
static ParseResult parseUniformClause(OpAsmParser &parser, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &uniformVars, SmallVectorImpl< Type > &uniformTypes)
uniform ::= uniform ( uniform-list ) uniform-list := uniform-val (, uniform-val)* uniform-val := ssa-...
static void printInReductionPrivateRegion(OpAsmPrinter &p, Operation *op, Region ®ion, ValueRange inReductionVars, TypeRange inReductionTypes, DenseBoolArrayAttr inReductionByref, ArrayAttr inReductionSyms, ValueRange privateVars, TypeRange privateTypes, ArrayAttr privateSyms, UnitAttr privateNeedsBarrier)
static LogicalResult verifyAllocateClause(Operation *op, ValueRange allocateVars, ValueRange allocatorVars, DenseI64ArrayAttr allocateAlignments, DenseI64ArrayAttr allocatePrivateIndices, ValueRange privateVars={}, ArrayAttr privateSyms=nullptr, bool requirePrivateIndices=false)
static void printSynchronizationHint(OpAsmPrinter &p, Operation *op, IntegerAttr hintAttr)
Prints a Synchronization Hint clause.
static void printGranularityClause(OpAsmPrinter &p, Operation *op, ClauseTypeAttr prescriptiveness, Value operand, mlir::Type operandType, StringRef(*stringifyClauseType)(ClauseType))
static ParseResult parseDependVarList(OpAsmParser &parser, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &dependVars, SmallVectorImpl< Type > &dependTypes, ArrayAttr &dependKinds, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &iteratedVars, SmallVectorImpl< Type > &iteratedTypes, ArrayAttr &iteratedKinds)
depend-entry-list ::= depend-entry | depend-entry-list , depend-entry depend-entry ::= depend-kind ->...
static void getTaskReductionEffects(Operation *op, SmallVectorImpl< MemoryEffects::EffectInstance > &effects)
static Operation * getParentInSameDialect(Operation *thisOp)
static void printUniformClause(OpAsmPrinter &p, Operation *op, ValueRange uniformVars, TypeRange uniformTypes)
Print Uniform Clauses.
static LogicalResult verifyCopyprivateVarList(Operation *op, OperandRange copyprivateVars, std::optional< ArrayAttr > copyprivateSyms)
Verifies CopyPrivate Clause.
static LogicalResult verifyAlignedClause(Operation *op, std::optional< ArrayAttr > alignments, OperandRange alignedVars)
static ParseResult parsePrivateRegion(OpAsmParser &parser, Region ®ion, llvm::SmallVectorImpl< OpAsmParser::UnresolvedOperand > &privateVars, llvm::SmallVectorImpl< Type > &privateTypes, ArrayAttr &privateSyms, UnitAttr &privateNeedsBarrier)
static void printNumTasksClause(OpAsmPrinter &p, Operation *op, ClauseNumTasksTypeAttr numTasksMod, Value numTasks, mlir::Type numTasksType)
static void printLoopTransformClis(OpAsmPrinter &p, TileOp op, OperandRange generatees, OperandRange applyees)
static ParseResult parseDynGroupprivateClause(OpAsmParser &parser, AccessGroupModifierAttr &accessGroupAttr, FallbackModifierAttr &fallbackAttr, std::optional< OpAsmParser::UnresolvedOperand > &dynGroupprivateSize, Type &sizeType)
static void printPrivateRegion(OpAsmPrinter &p, Operation *op, Region ®ion, ValueRange privateVars, TypeRange privateTypes, ArrayAttr privateSyms, UnitAttr privateNeedsBarrier)
static ParseResult parseSplitIteratedList(OpAsmParser &parser, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &iteratedVars, SmallVectorImpl< Type > &iteratedTypes, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &plainVars, SmallVectorImpl< Type > &plainTypes, ParsePrefixFn &&parsePrefix)
static void printTaskReductionRegion(OpAsmPrinter &p, Operation *op, Region ®ion, ValueRange taskReductionVars, TypeRange taskReductionTypes, DenseBoolArrayAttr taskReductionByref, ArrayAttr taskReductionSyms)
static LogicalResult verifyMapInfoForMapClause(Operation *op, mlir::omp::MapInfoOp mapInfoOp, llvm::DenseSet< mlir::TypedValue< mlir::omp::PointerLikeType > > &updateToVars, llvm::DenseSet< mlir::TypedValue< mlir::omp::PointerLikeType > > &updateFromVars)
static void getPrivatisationEffects(Operation *op, SmallVectorImpl< MemoryEffects::EffectInstance > &effects)
Privatisation may read the original as a mold or firstprivate copy source. Any lastprivate copy-back ...
static void printInReductionPrivateReductionRegion(OpAsmPrinter &p, Operation *op, Region ®ion, ValueRange inReductionVars, TypeRange inReductionTypes, DenseBoolArrayAttr inReductionByref, ArrayAttr inReductionSyms, ValueRange privateVars, TypeRange privateTypes, ArrayAttr privateSyms, UnitAttr privateNeedsBarrier, ArrayAttr reductionMods, ValueRange reductionVars, TypeRange reductionTypes, DenseBoolArrayAttr reductionByref, ArrayAttr reductionSyms)
static void getBarrierEffects(llvm::SmallVectorImpl< SideEffects::EffectInstance< MemoryEffects::Effect > > &effects)
static LogicalResult verifyOrderedParent(Operation &op)
static void printOrderClause(OpAsmPrinter &p, Operation *op, ClauseOrderKindAttr order, OrderModifierAttr orderMod)
static ParseResult parseBlockArgClause(OpAsmParser &parser, llvm::SmallVectorImpl< OpAsmParser::Argument > &entryBlockArgs, StringRef keyword, std::optional< MapParseArgs > mapArgs)
static LogicalResult verifyPrivateVarsMapping(TargetOp targetOp)
static ParseResult parseScheduleClause(OpAsmParser &parser, ClauseScheduleKindAttr &scheduleAttr, ScheduleModifierAttr &scheduleMod, UnitAttr &scheduleSimd, std::optional< OpAsmParser::UnresolvedOperand > &chunkSize, Type &chunkType)
schedule ::= schedule ( sched-list ) sched-list ::= sched-val | sched-val sched-list | sched-val ,...
static LogicalResult verifyDynGroupprivateClause(Operation *op, AccessGroupModifierAttr accessGroup, FallbackModifierAttr fallback, Value dynGroupprivateSize)
static LogicalResult verifyLinearModifiers(Operation *op, std::optional< ArrayAttr > linearModifiers, OperandRange linearVars, bool isDeclareSimd=false)
OpenMP 5.2, Section 5.4.6: "A linear-modifier may be specified as ref or uval only on a declare simd ...
static void printClauseAttr(OpAsmPrinter &p, Operation *op, ClauseAttr attr)
static LogicalResult verifyLinearSyms(OpType op)
Verifies that each linear variable has a linear privatizer.
static ParseResult parseAllocateAndAllocator(OpAsmParser &parser, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &allocateVars, SmallVectorImpl< Type > &allocateTypes, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &allocatorVars, SmallVectorImpl< Type > &allocatorTypes)
Parse an allocate clause with allocators and a list of operands with types.
static void printMembersIndex(OpAsmPrinter &p, MapInfoOp op, ArrayAttr membersIdx)
static void getReductionEffects(Operation *op, SmallVectorImpl< MemoryEffects::EffectInstance > &effects)
Reductions initialise private accumulators and combine them into the original variables.
static ParseResult parseClauseWithRegionArgs(OpAsmParser &parser, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &operands, SmallVectorImpl< Type > &types, SmallVectorImpl< OpAsmParser::Argument > ®ionPrivateArgs, ArrayAttr *symbols=nullptr, DenseI64ArrayAttr *mapIndices=nullptr, DenseBoolArrayAttr *byref=nullptr, ArrayAttr *modifier=nullptr, UnitAttr *needsBarrier=nullptr)
static void printCaptureType(OpAsmPrinter &p, Operation *op, VariableCaptureKindAttr mapCaptureType)
static LogicalResult verifyReductionModifiers(Operation *op, OperandRange reductionVars, ArrayAttr reductionMods)
Verify the per-variable modifier list has one entry per reduction variable.
static void getTaskSchedulingPointEffects(llvm::SmallVectorImpl< SideEffects::EffectInstance< MemoryEffects::Effect > > &effects)
static LogicalResult verifyNumTeamsClause(Operation *op, Value numTeamsLower, OperandRange numTeamsUpperVars)
static bool opInGlobalImplicitParallelRegion(Operation *op)
static void printTargetOpRegion(OpAsmPrinter &p, Operation *op, Region ®ion, ValueRange hasDeviceAddrVars, TypeRange hasDeviceAddrTypes, ValueRange hostEvalVars, TypeRange hostEvalTypes, ValueRange mapVars, TypeRange mapTypes, ValueRange privateVars, TypeRange privateTypes, ArrayAttr privateSyms, UnitAttr privateNeedsBarrier, DenseI64ArrayAttr privateMaps)
static void printUseDeviceAddrUseDevicePtrRegion(OpAsmPrinter &p, Operation *op, Region ®ion, ValueRange useDeviceAddrVars, TypeRange useDeviceAddrTypes, ValueRange useDevicePtrVars, TypeRange useDevicePtrTypes)
static LogicalResult verifyMapClause(Operation *op, OperandRange mapVars, OperandRange mapIterated)
static LogicalResult verifyPrivateVarList(OpType &op)
static ParseResult parseNumTasksClause(OpAsmParser &parser, ClauseNumTasksTypeAttr &numTasksMod, std::optional< OpAsmParser::UnresolvedOperand > &numTasks, Type &numTasksType)
LogicalResult verifyAlignment(Operation &op, std::optional< uint64_t > alignment)
Verifies align clause in allocate directive.
static ParseResult parseAlignedClause(OpAsmParser &parser, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &alignedVars, SmallVectorImpl< Type > &alignedTypes, ArrayAttr &alignmentsAttr)
aligned ::= aligned ( aligned-list ) aligned-list := aligned-val | aligned-val aligned-list aligned-v...
static ParseResult parseLinearClause(OpAsmParser &parser, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &linearVars, SmallVectorImpl< Type > &linearTypes, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &linearStepVars, SmallVectorImpl< Type > &linearStepTypes, ArrayAttr &linearModifiers, ArrayAttr &linearSyms)
linear ::= linear ( linear-list ) linear-list := linear-val | linear-val linear-list linear-val := ss...
static LogicalResult checkApplyeesNesting(TileOp op)
Check properties of the loop nest consisting of the transformation's applyees:
static ParseResult parseCaptureType(OpAsmParser &parser, VariableCaptureKindAttr &mapCaptureType)
static ParseResult parseTaskReductionRegion(OpAsmParser &parser, Region ®ion, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &taskReductionVars, SmallVectorImpl< Type > &taskReductionTypes, DenseBoolArrayAttr &taskReductionByref, ArrayAttr &taskReductionSyms)
static ParseResult parseGrainsizeClause(OpAsmParser &parser, ClauseGrainsizeTypeAttr &grainsizeMod, std::optional< OpAsmParser::UnresolvedOperand > &grainsize, Type &grainsizeType)
static ParseResult parseCopyprivate(OpAsmParser &parser, SmallVectorImpl< OpAsmParser::UnresolvedOperand > ©privateVars, SmallVectorImpl< Type > ©privateTypes, ArrayAttr ©privateSyms)
copyprivate-entry-list ::= copyprivate-entry | copyprivate-entry-list , copyprivate-entry copyprivate...
static ParseResult parseInReductionClause(OpAsmParser &parser, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &inReductionVars, SmallVectorImpl< Type > &inReductionTypes, DenseBoolArrayAttr &inReductionByref, ArrayAttr &inReductionSyms)
Parses an in_reduction clause for an operation that does not give its list items entry block argument...
static LogicalResult verifyMapInfoDefinedArgs(Operation *op, StringRef clauseName, OperandRange vars)
static void printGrainsizeClause(OpAsmPrinter &p, Operation *op, ClauseGrainsizeTypeAttr grainsizeMod, Value grainsize, mlir::Type grainsizeType)
static ParseResult verifyScheduleModifiers(OpAsmParser &parser, SmallVectorImpl< SmallString< 12 > > &modifiers)
static Type getElementType(Type type, ArrayRef< int32_t > indices, function_ref< InFlightDiagnostic(StringRef)> emitErrorFn)
Walks the given type hierarchy with the given indices, potentially down to component granularity,...
static bool isUnique(It begin, It end)
static LogicalResult emit(SolverOp solver, const SMTEmissionOptions &options, mlir::raw_indented_ostream &stream)
Emit the SMT operations in the given 'solver' to the 'stream'.
static SmallVector< Value > getTileSizes(Location loc, x86::amx::TileType tType, RewriterBase &rewriter)
Maps the 2-dim vector shape to the two 16-bit tile sizes.
This base class exposes generic asm parser hooks, usable across the various derived parsers.
virtual ParseResult parseMinus()=0
Parse a '-' token.
@ Paren
Parens surrounding zero or more operands.
@ None
Zero or more operands with no delimiters.
virtual ParseResult parseColonTypeList(SmallVectorImpl< Type > &result)=0
Parse a colon followed by a type list, which must have at least one type.
virtual Builder & getBuilder() const =0
Return a builder which provides useful access to MLIRContext, global objects like types and attribute...
virtual ParseResult parseCommaSeparatedList(Delimiter delimiter, function_ref< ParseResult()> parseElementFn, StringRef contextMessage=StringRef())=0
Parse a list of comma-separated items with an optional delimiter.
virtual ParseResult parseOptionalAttrDict(NamedAttrList &result)=0
Parse a named dictionary into 'result' if it is present.
virtual ParseResult parseOptionalEqual()=0
Parse a = token if present.
virtual ParseResult parseOptionalKeyword(StringRef keyword)=0
Parse the given keyword if present.
MLIRContext * getContext() const
virtual ParseResult parseRParen()=0
Parse a ) token.
virtual InFlightDiagnostic emitError(SMLoc loc, const Twine &message={})=0
Emit a diagnostic at the specified location and return failure.
virtual ParseResult parseOptionalColon()=0
Parse a : token if present.
virtual ParseResult parseLSquare()=0
Parse a [ token.
virtual ParseResult parseRSquare()=0
Parse a ] token.
ParseResult parseInteger(IntT &result)
Parse an integer value from the stream.
virtual ParseResult parseOptionalArrow()=0
Parse a '->' token if present.
virtual ParseResult parseLess()=0
Parse a '<' token.
virtual ParseResult parseEqual()=0
Parse a = token.
virtual ParseResult parseColonType(Type &result)=0
Parse a colon followed by a type.
virtual SMLoc getCurrentLocation()=0
Get the location of the next token and store it into the argument.
virtual ParseResult parseOptionalComma()=0
Parse a , token if present.
virtual ParseResult parseColon()=0
Parse a : token.
virtual SMLoc getNameLoc() const =0
Return the location of the original name token.
virtual ParseResult parseOptionalLess()=0
Parse a '<' token if present.
virtual ParseResult parseArrow()=0
Parse a '->' token.
virtual ParseResult parseLParen()=0
Parse a ( token.
virtual ParseResult parseType(Type &result)=0
Parse a type.
virtual ParseResult parseComma()=0
Parse a , token.
virtual ParseResult parseOptionalLParen()=0
Parse a ( token if present.
ParseResult parseKeyword(StringRef keyword)
Parse a given keyword.
virtual ParseResult parseOptionalLSquare()=0
Parse a [ token if present.
virtual ParseResult parseAttribute(Attribute &result, Type type={})=0
Parse an arbitrary attribute of a given type and return it in result.
Attributes are known-constant values of operations.
This class represents an argument of a Block.
Block represents an ordered list of Operations.
MutableArrayRef< BlockArgument > BlockArgListType
ValueTypeRange< BlockArgListType > getArgumentTypes()
Return a range containing the types of the arguments for this block.
unsigned getNumSuccessors()
BlockArgument getArgument(unsigned i)
unsigned getNumArguments()
SuccessorRange getSuccessors()
Operation * getTerminator()
Get the terminator operation of this block.
bool mightHaveTerminator()
Return "true" if this block might have a terminator.
BlockArgListType getArguments()
IntegerAttr getI64IntegerAttr(int64_t value)
IntegerType getIntegerType(unsigned width)
MLIRContext * getContext() const
Attr getAttr(Args &&...args)
Get or construct an instance of the attribute Attr with provided arguments.
Diagnostic & append(Arg1 &&arg1, Arg2 &&arg2, Args &&...args)
Append arguments to the diagnostic.
Diagnostic & appendOp(Operation &op, const OpPrintingFlags &flags)
Append an operation with the given printing flags.
A class for computing basic dominance information.
bool dominates(Operation *a, Operation *b) const
Return true if operation A dominates operation B, i.e.
A symbol reference with a reference path containing a single element.
This class represents a diagnostic that is inflight and set to be reported.
Diagnostic & attachNote(std::optional< Location > noteLoc=std::nullopt)
Attaches a note to this diagnostic.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
MLIRContext is the top-level object for a collection of MLIR operations.
NamedAttribute represents a combination of a name and an Attribute value.
StringAttr getName() const
Return the name of the attribute.
Attribute getValue() const
Return the value of the attribute.
The OpAsmParser has methods for interacting with the asm parser: parsing things from it,...
virtual ParseResult parseRegion(Region ®ion, ArrayRef< Argument > arguments={}, bool enableNameShadowing=false)=0
Parses a region.
virtual ParseResult parseArgument(Argument &result, bool allowType=false, bool allowAttrs=false)=0
Parse a single argument with the following syntax:
virtual ParseResult parseArgumentList(SmallVectorImpl< Argument > &result, Delimiter delimiter=Delimiter::None, bool allowType=false, bool allowAttrs=false)=0
Parse zero or more arguments with a specified surrounding delimiter.
virtual ParseResult resolveOperand(const UnresolvedOperand &operand, Type type, SmallVectorImpl< Value > &result)=0
Resolve an operand to an SSA value, emitting an error on failure.
ParseResult resolveOperands(Operands &&operands, Type type, SmallVectorImpl< Value > &result)
Resolve a list of operands to SSA values, emitting an error on failure, or appending the results to t...
virtual ParseResult parseOperand(UnresolvedOperand &result, bool allowResultNumber=true)=0
Parse a single SSA value operand name along with a result number if allowResultNumber is true.
virtual ParseResult parseOperandList(SmallVectorImpl< UnresolvedOperand > &result, Delimiter delimiter=Delimiter::None, bool allowResultNumber=true, int requiredOperandCount=-1)=0
Parse zero or more SSA comma-separated operand references with a specified surrounding delimiter,...
This is a pure-virtual base class that exposes the asmprinter hooks necessary to implement a custom p...
virtual void printOptionalAttrDict(ArrayRef< NamedAttribute > attrs, ArrayRef< StringRef > elidedAttrs={})=0
If the specified operation has attributes, print out an attribute dictionary with their values.
virtual void printRegion(Region &blocks, bool printEntryBlockArgs=true, bool printBlockTerminators=true, bool printEmptyBlock=false)=0
Prints a region.
virtual void printRegionArgument(BlockArgument arg, ArrayRef< NamedAttribute > argAttrs={}, bool omitType=false)=0
Print a block argument in the usual format of: ssaName : type {attr1=42} loc("here") where location p...
virtual void printOperand(Value value)=0
Print implementations for various things an operation contains.
RAII guard to reset the insertion point of the builder when destroyed.
This class helps build Operations.
Block * createBlock(Region *parent, Region::iterator insertPt={}, TypeRange argTypes={}, ArrayRef< Location > locs={})
Add new block with 'argTypes' arguments and set the insertion point to the end of it.
This class represents an operand of an operation.
Set of flags used to control the behavior of the various IR print methods (e.g.
This class provides the API for ops that are known to be isolated from above.
This class provides the API for ops that are known to be terminators.
This class indicates that the regions associated with this op don't have terminators.
This class implements the operand iterators for the Operation class.
type_range getType() const
Operation is the basic unit of execution within MLIR.
Dialect * getDialect()
Return the dialect this operation is associated with, or nullptr if the associated dialect is not loa...
Region & getRegion(unsigned index)
Returns the region held by this operation at position 'index'.
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
Block * getBlock()
Returns the operation block that contains this operation.
unsigned getNumRegions()
Returns the number of regions held by this operation.
Location getLoc()
The source location the operation was defined or derived from.
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
OpTy getParentOfType()
Return the closest surrounding parent operation that is of type 'OpTy'.
MutableArrayRef< Region > getRegions()
Returns the regions held by this operation.
operand_range getOperands()
Returns an iterator on the underlying Value's.
user_range getUsers()
Returns a range of all users.
Region * getParentRegion()
Returns the region to which the instruction belongs.
MLIRContext * getContext()
Return the context this operation is associated with.
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
This class represents a point being branched from in the methods of the RegionBranchOpInterface.
bool isParent() const
Returns true if branching from the parent op.
This class represents a successor of a region.
Region * getSuccessor() const
Return the given region successor.
bool isOperation() const
Return true if the successor is an operation.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
BlockArgListType getArguments()
OpIterator op_begin()
Return iterators that walk the operations nested directly within this region.
bool isAncestor(Region *other)
Return true if this region is ancestor of the other region.
iterator_range< OpIterator > getOps()
unsigned getNumArguments()
Location getLoc()
Return a location for this region.
BlockArgument getArgument(unsigned i)
Operation * getParentOp()
Return the parent operation this region is attached to.
BlockListType & getBlocks()
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replace the results of the given (original) op with a new op that is created without verification (re...
This class represents a specific instance of an effect.
static DerivedEffect * get()
This class represents a collection of SymbolTables.
virtual Operation * lookupNearestSymbolFrom(Operation *from, StringAttr symbol)
Returns the operation registered with the given symbol name within the closest parent operation of,...
static Operation * lookupNearestSymbolFrom(Operation *from, StringAttr symbol)
Returns the operation registered with the given symbol name within the closest parent operation of,...
This class provides an abstraction over the various different ranges of value types.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
This class provides an abstraction over the different types of ranges over Values.
type_range getType() const
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
MLIRContext * getContext() const
Utility to get the associated MLIRContext that this value is defined in.
Type getType() const
Return the type of this value.
use_range getUses() const
Returns a range of all uses, which is useful for iterating over all uses.
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
A utility result that is used to signal how to proceed with an ongoing walk:
static WalkResult advance()
static DenseArrayAttrImpl get(MLIRContext *context, ArrayRef< bool > content)
ArrayRef< T > asArrayRef() const
bool isReachableFromEntry(Block *a) const
Return true if the specified block is reachable from the entry block of its region.
Operation * getOwner() const
Return the owner of this operand.
TargetEnterDataOperands TargetEnterExitUpdateDataOperands
omp.target_enter_data, omp.target_exit_data and omp.target_update take the same clauses,...
std::tuple< NewCliOp, OpOperand *, OpOperand * > decodeCli(mlir::Value cli)
Find the omp.new_cli, generator, and consumer of a canonical loop info.
ClauseProcBindKind convertProcBindKind(llvm::omp::ProcBindKind kind)
Convert a proc_bind kind from the LLVM frontend enum to the corresponding OpenMP dialect enum.
Include the generated interface declarations.
bool matchPattern(Value value, const Pattern &pattern)
Entry point for matching a pattern over a Value.
detail::DenseArrayAttrImpl< int64_t > DenseI64ArrayAttr
function_ref< void(Value, StringRef)> OpAsmSetValueNameFn
A functor used to set the name of the start of a result group of an operation.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
llvm::DenseSet< ValueT, ValueInfoT > DenseSet
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
bool isPure(Operation *op)
Returns true if the given operation is pure, i.e., is speculatable that does not touch memory.
detail::constant_int_predicate_matcher m_Zero()
Matches a constant scalar / vector splat / tensor splat integer zero.
std::conditional_t< std::is_same_v< Ty, mlir::Type >, mlir::Value, detail::TypedValue< Ty > > TypedValue
If Ty is mlir::Type this will select Value instead of having a wrapper around it.
llvm::TypeSwitch< T, ResultT > TypeSwitch
SmallVector< Loops, 8 > tile(ArrayRef< scf::ForOp > forOps, ArrayRef< Value > sizes, ArrayRef< scf::ForOp > targets)
Performs tiling fo imperfectly nested loops (with interchange) by strip-mining the forOps by sizes an...
detail::DenseArrayAttrImpl< bool > DenseBoolArrayAttr
detail::constant_op_matcher m_Constant()
Matches a constant foldable operation.
llvm::function_ref< Fn > function_ref
function_ref< void(Block *, StringRef)> OpAsmSetBlockNameFn
A functor used to set the name of blocks in regions directly nested under an operation.
This is the representation of an operand reference.
This class provides APIs and verifiers for ops with regions having a single block.
This represents an operation in an abstracted form, suitable for use with the builder APIs.
T & getOrAddProperties()
Get (or create) the properties of the provided type to be set on the operation on creation.
void addOperands(ValueRange newOperands)
void addAttributes(ArrayRef< NamedAttribute > newAttributes)
Add an array of named attributes.
void addAttribute(StringRef name, Attribute attr)
Add an attribute with the specified name.
void addTypes(ArrayRef< Type > newTypes)
SmallVector< std::unique_ptr< Region >, 1 > regions
Regions that the op will hold.
Region * addRegion()
Create a region that should be attached to the operation.
Extended TargetOperands with kernel_type attribute.
TargetExecModeAttr kernelType
Kernel execution mode for the target region.