Debian Codegraph @

flang/lib/Optimizer/HLFIR/IR/HLFIROps.cpp

raw
1 //===-- HLFIROps.cpp ------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Coding style: https://mlir.llvm.org/getting_started/DeveloperGuide/
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "flang/Optimizer/HLFIR/HLFIROps.h"
14
15 #include "flang/Optimizer/Dialect/FIROpsSupport.h"
16 #include "flang/Optimizer/Dialect/FIRType.h"
17 #include "flang/Optimizer/Dialect/Support/FIRContext.h"
18 #include "flang/Optimizer/HLFIR/HLFIRDialect.h"
19 #include "mlir/IR/Builders.h"
20 #include "mlir/IR/BuiltinAttributes.h"
21 #include "mlir/IR/BuiltinTypes.h"
22 #include "mlir/IR/DialectImplementation.h"
23 #include "mlir/IR/Matchers.h"
24 #include "mlir/IR/OpImplementation.h"
25 #include "llvm/ADT/APInt.h"
26 #include "llvm/ADT/TypeSwitch.h"
27 #include "llvm/Support/CommandLine.h"
28 #include <iterator>
29 #include <mlir/Interfaces/SideEffectInterfaces.h>
30 #include <optional>
31 #include <tuple>
32
33 static llvm::cl::opt<bool> useStrictIntrinsicVerifier(
34 "strict-intrinsic-verifier", llvm::cl::init(false),
35 llvm::cl::desc("use stricter verifier for HLFIR intrinsic operations"));
36
37 /// generic implementation of the memory side effects interface for hlfir
38 /// transformational intrinsic operations
39 static void
40 getIntrinsicEffects(mlir::Operation *self,
41 llvm::SmallVectorImpl<mlir::SideEffects::EffectInstance<
42 mlir::MemoryEffects::Effect>> &effects) {
43 // allocation effect if we return an expr
44 assert(self->getNumResults() == 1 &&
45 "hlfir intrinsic ops only produce 1 result");
46 if (mlir::isa<hlfir::ExprType>(self->getResult(0).getType()))
47 effects.emplace_back(mlir::MemoryEffects::Allocate::get(),
48 self->getOpResult(0),
49 mlir::SideEffects::DefaultResource::get());
50
51 // read effect if we read from a pointer or refference type
52 // or a box who'se pointer is read from inside of the intrinsic so that
53 // loop conflicts can be detected in code like
54 // hlfir.region_assign {
55 // %2 = hlfir.transpose %0#0 : (!fir.box<!fir.array<?x?xf32>>) ->
56 // !hlfir.expr<?x?xf32> hlfir.yield %2 : !hlfir.expr<?x?xf32> cleanup {
57 // hlfir.destroy %2 : !hlfir.expr<?x?xf32>
58 // }
59 // } to {
60 // hlfir.yield %0#0 : !fir.box<!fir.array<?x?xf32>>
61 // }
62 for (mlir::OpOperand &operand : self->getOpOperands()) {
63 mlir::Type opTy = operand.get().getType();
64 if (fir::isa_ref_type(opTy) || fir::isa_box_type(opTy))
65 effects.emplace_back(mlir::MemoryEffects::Read::get(), &operand,
66 mlir::SideEffects::DefaultResource::get());
67 }
68 }
69
70 //===----------------------------------------------------------------------===//
71 // DeclareOp
72 //===----------------------------------------------------------------------===//
73
74 /// Is this a fir.[ref/ptr/heap]<fir.[box/class]<fir.heap<T>>> type?
75 static bool isAllocatableBoxRef(mlir::Type type) {
76 fir::BaseBoxType boxType =
77 mlir::dyn_cast_or_null<fir::BaseBoxType>(fir::dyn_cast_ptrEleTy(type));
78 return boxType && mlir::isa<fir::HeapType>(boxType.getEleTy());
79 }
80
81 llvm::LogicalResult hlfir::AssignOp::verify() {
82 mlir::Type lhsType = getLhs().getType();
83 if (isAllocatableAssignment() && !isAllocatableBoxRef(lhsType))
84 return emitOpError("lhs must be an allocatable when `realloc` is set");
85 if (mustKeepLhsLengthInAllocatableAssignment() &&
86 !(isAllocatableAssignment() &&
87 mlir::isa<fir::CharacterType>(hlfir::getFortranElementType(lhsType))))
88 return emitOpError("`realloc` must be set and lhs must be a character "
89 "allocatable when `keep_lhs_length_if_realloc` is set");
90 return mlir::success();
91 }
92
93 //===----------------------------------------------------------------------===//
94 // DeclareOp
95 //===----------------------------------------------------------------------===//
96
97 /// Given a FIR memory type, and information about non default lower bounds, get
98 /// the related HLFIR variable type.
99 mlir::Type hlfir::DeclareOp::getHLFIRVariableType(mlir::Type inputType,
100 bool hasExplicitLowerBounds) {
101 mlir::Type type = fir::unwrapRefType(inputType);
102 if (mlir::isa<fir::BaseBoxType>(type))
103 return inputType;
104 if (auto charType = mlir::dyn_cast<fir::CharacterType>(type))
105 if (charType.hasDynamicLen())
106 return fir::BoxCharType::get(charType.getContext(), charType.getFKind());
107
108 auto seqType = mlir::dyn_cast<fir::SequenceType>(type);
109 bool hasDynamicExtents =
110 seqType && fir::sequenceWithNonConstantShape(seqType);
111 mlir::Type eleType = seqType ? seqType.getEleTy() : type;
112 bool hasDynamicLengthParams = fir::characterWithDynamicLen(eleType) ||
113 fir::isRecordWithTypeParameters(eleType);
114 if (hasExplicitLowerBounds || hasDynamicExtents || hasDynamicLengthParams)
115 return fir::BoxType::get(type);
116 return inputType;
117 }
118
119 static bool hasExplicitLowerBounds(mlir::Value shape) {
120 return shape &&
121 mlir::isa<fir::ShapeShiftType, fir::ShiftType>(shape.getType());
122 }
123
124 void hlfir::DeclareOp::build(mlir::OpBuilder &builder,
125 mlir::OperationState &result, mlir::Value memref,
126 llvm::StringRef uniq_name, mlir::Value shape,
127 mlir::ValueRange typeparams,
128 mlir::Value dummy_scope,
129 fir::FortranVariableFlagsAttr fortran_attrs,
130 cuf::DataAttributeAttr data_attr) {
131 auto nameAttr = builder.getStringAttr(uniq_name);
132 mlir::Type inputType = memref.getType();
133 bool hasExplicitLbs = hasExplicitLowerBounds(shape);
134 mlir::Type hlfirVariableType =
135 getHLFIRVariableType(inputType, hasExplicitLbs);
136 build(builder, result, {hlfirVariableType, inputType}, memref, shape,
137 typeparams, dummy_scope, nameAttr, fortran_attrs, data_attr);
138 }
139
140 llvm::LogicalResult hlfir::DeclareOp::verify() {
141 if (getMemref().getType() != getResult(1).getType())
142 return emitOpError("second result type must match input memref type");
143 mlir::Type hlfirVariableType = getHLFIRVariableType(
144 getMemref().getType(), hasExplicitLowerBounds(getShape()));
145 if (hlfirVariableType != getResult(0).getType())
146 return emitOpError("first result type is inconsistent with variable "
147 "properties: expected ")
148 << hlfirVariableType;
149 // The rest of the argument verification is done by the
150 // FortranVariableInterface verifier.
151 auto fortranVar =
152 mlir::cast<fir::FortranVariableOpInterface>(this->getOperation());
153 return fortranVar.verifyDeclareLikeOpImpl(getMemref());
154 }
155
156 //===----------------------------------------------------------------------===//
157 // DesignateOp
158 //===----------------------------------------------------------------------===//
159
160 void hlfir::DesignateOp::build(
161 mlir::OpBuilder &builder, mlir::OperationState &result,
162 mlir::Type result_type, mlir::Value memref, llvm::StringRef component,
163 mlir::Value component_shape, llvm::ArrayRef<Subscript> subscripts,
164 mlir::ValueRange substring, std::optional<bool> complex_part,
165 mlir::Value shape, mlir::ValueRange typeparams,
166 fir::FortranVariableFlagsAttr fortran_attrs) {
167 auto componentAttr =
168 component.empty() ? mlir::StringAttr{} : builder.getStringAttr(component);
169 llvm::SmallVector<mlir::Value> indices;
170 llvm::SmallVector<bool> isTriplet;
171 for (auto subscript : subscripts) {
172 if (auto *triplet = std::get_if<Triplet>(&subscript)) {
173 isTriplet.push_back(true);
174 indices.push_back(std::get<0>(*triplet));
175 indices.push_back(std::get<1>(*triplet));
176 indices.push_back(std::get<2>(*triplet));
177 } else {
178 isTriplet.push_back(false);
179 indices.push_back(std::get<mlir::Value>(subscript));
180 }
181 }
182 auto isTripletAttr =
183 mlir::DenseBoolArrayAttr::get(builder.getContext(), isTriplet);
184 auto complexPartAttr =
185 complex_part.has_value()
186 ? mlir::BoolAttr::get(builder.getContext(), *complex_part)
187 : mlir::BoolAttr{};
188 build(builder, result, result_type, memref, componentAttr, component_shape,
189 indices, isTripletAttr, substring, complexPartAttr, shape, typeparams,
190 fortran_attrs);
191 }
192
193 void hlfir::DesignateOp::build(mlir::OpBuilder &builder,
194 mlir::OperationState &result,
195 mlir::Type result_type, mlir::Value memref,
196 mlir::ValueRange indices,
197 mlir::ValueRange typeparams,
198 fir::FortranVariableFlagsAttr fortran_attrs) {
199 llvm::SmallVector<bool> isTriplet(indices.size(), false);
200 auto isTripletAttr =
201 mlir::DenseBoolArrayAttr::get(builder.getContext(), isTriplet);
202 build(builder, result, result_type, memref,
203 /*componentAttr=*/mlir::StringAttr{}, /*component_shape=*/mlir::Value{},
204 indices, isTripletAttr, /*substring*/ mlir::ValueRange{},
205 /*complexPartAttr=*/mlir::BoolAttr{}, /*shape=*/mlir::Value{},
206 typeparams, fortran_attrs);
207 }
208
209 static mlir::ParseResult parseDesignatorIndices(
210 mlir::OpAsmParser &parser,
211 llvm::SmallVectorImpl<mlir::OpAsmParser::UnresolvedOperand> &indices,
212 mlir::DenseBoolArrayAttr &isTripletAttr) {
213 llvm::SmallVector<bool> isTriplet;
214 if (mlir::succeeded(parser.parseOptionalLParen())) {
215 do {
216 mlir::OpAsmParser::UnresolvedOperand i1, i2, i3;
217 if (parser.parseOperand(i1))
218 return mlir::failure();
219 indices.push_back(i1);
220 if (mlir::succeeded(parser.parseOptionalColon())) {
221 if (parser.parseOperand(i2) || parser.parseColon() ||
222 parser.parseOperand(i3))
223 return mlir::failure();
224 indices.push_back(i2);
225 indices.push_back(i3);
226 isTriplet.push_back(true);
227 } else {
228 isTriplet.push_back(false);
229 }
230 } while (mlir::succeeded(parser.parseOptionalComma()));
231 if (parser.parseRParen())
232 return mlir::failure();
233 }
234 isTripletAttr = mlir::DenseBoolArrayAttr::get(parser.getContext(), isTriplet);
235 return mlir::success();
236 }
237
238 static void
239 printDesignatorIndices(mlir::OpAsmPrinter &p, hlfir::DesignateOp designateOp,
240 mlir::OperandRange indices,
241 const mlir::DenseBoolArrayAttr &isTripletAttr) {
242 if (!indices.empty()) {
243 p << '(';
244 unsigned i = 0;
245 for (auto isTriplet : isTripletAttr.asArrayRef()) {
246 if (isTriplet) {
247 assert(i + 2 < indices.size() && "ill-formed indices");
248 p << indices[i] << ":" << indices[i + 1] << ":" << indices[i + 2];
249 i += 3;
250 } else {
251 p << indices[i++];
252 }
253 if (i != indices.size())
254 p << ", ";
255 }
256 p << ')';
257 }
258 }
259
260 static mlir::ParseResult
261 parseDesignatorComplexPart(mlir::OpAsmParser &parser,
262 mlir::BoolAttr &complexPart) {
263 if (mlir::succeeded(parser.parseOptionalKeyword("imag")))
264 complexPart = mlir::BoolAttr::get(parser.getContext(), true);
265 else if (mlir::succeeded(parser.parseOptionalKeyword("real")))
266 complexPart = mlir::BoolAttr::get(parser.getContext(), false);
267 return mlir::success();
268 }
269
270 static void printDesignatorComplexPart(mlir::OpAsmPrinter &p,
271 hlfir::DesignateOp designateOp,
272 mlir::BoolAttr complexPartAttr) {
273 if (complexPartAttr) {
274 if (complexPartAttr.getValue())
275 p << "imag";
276 else
277 p << "real";
278 }
279 }
280
281 llvm::LogicalResult hlfir::DesignateOp::verify() {
282 mlir::Type memrefType = getMemref().getType();
283 mlir::Type baseType = getFortranElementOrSequenceType(memrefType);
284 mlir::Type baseElementType = fir::unwrapSequenceType(baseType);
285 unsigned numSubscripts = getIsTriplet().size();
286 unsigned subscriptsRank =
287 llvm::count_if(getIsTriplet(), [](bool isTriplet) { return isTriplet; });
288 unsigned outputRank = 0;
289 mlir::Type outputElementType;
290 bool hasBoxComponent;
291 if (getComponent()) {
292 auto component = getComponent().value();
293 auto recType = mlir::dyn_cast<fir::RecordType>(baseElementType);
294 if (!recType)
295 return emitOpError(
296 "component must be provided only when the memref is a derived type");
297 unsigned fieldIdx = recType.getFieldIndex(component);
298 if (fieldIdx > recType.getNumFields()) {
299 return emitOpError("component ")
300 << component << " is not a component of memref element type "
301 << recType;
302 }
303 mlir::Type fieldType = recType.getType(fieldIdx);
304 mlir::Type componentBaseType = getFortranElementOrSequenceType(fieldType);
305 hasBoxComponent = mlir::isa<fir::BaseBoxType>(fieldType);
306 if (mlir::isa<fir::SequenceType>(componentBaseType) &&
307 mlir::isa<fir::SequenceType>(baseType) &&
308 (numSubscripts == 0 || subscriptsRank > 0))
309 return emitOpError("indices must be provided and must not contain "
310 "triplets when both memref and component are arrays");
311 if (numSubscripts != 0) {
312 if (!mlir::isa<fir::SequenceType>(componentBaseType))
313 return emitOpError("indices must not be provided if component appears "
314 "and is not an array component");
315 if (!getComponentShape())
316 return emitOpError(
317 "component_shape must be provided when indexing a component");
318 mlir::Type compShapeType = getComponentShape().getType();
319 unsigned componentRank =
320 mlir::cast<fir::SequenceType>(componentBaseType).getDimension();
321 auto shapeType = mlir::dyn_cast<fir::ShapeType>(compShapeType);
322 auto shapeShiftType = mlir::dyn_cast<fir::ShapeShiftType>(compShapeType);
323 if (!((shapeType && shapeType.getRank() == componentRank) ||
324 (shapeShiftType && shapeShiftType.getRank() == componentRank)))
325 return emitOpError("component_shape must be a fir.shape or "
326 "fir.shapeshift with the rank of the component");
327 if (numSubscripts > componentRank)
328 return emitOpError("indices number must match array component rank");
329 }
330 if (auto baseSeqType = mlir::dyn_cast<fir::SequenceType>(baseType))
331 // This case must come first to cover "array%array_comp(i, j)" that has
332 // subscripts for the component but whose rank come from the base.
333 outputRank = baseSeqType.getDimension();
334 else if (numSubscripts != 0)
335 outputRank = subscriptsRank;
336 else if (auto componentSeqType =
337 mlir::dyn_cast<fir::SequenceType>(componentBaseType))
338 outputRank = componentSeqType.getDimension();
339 outputElementType = fir::unwrapSequenceType(componentBaseType);
340 } else {
341 outputElementType = baseElementType;
342 unsigned baseTypeRank =
343 mlir::isa<fir::SequenceType>(baseType)
344 ? mlir::cast<fir::SequenceType>(baseType).getDimension()
345 : 0;
346 if (numSubscripts != 0) {
347 if (baseTypeRank != numSubscripts)
348 return emitOpError("indices number must match memref rank");
349 outputRank = subscriptsRank;
350 } else if (auto baseSeqType = mlir::dyn_cast<fir::SequenceType>(baseType)) {
351 outputRank = baseSeqType.getDimension();
352 }
353 }
354
355 if (!getSubstring().empty()) {
356 if (!mlir::isa<fir::CharacterType>(outputElementType))
357 return emitOpError("memref or component must have character type if "
358 "substring indices are provided");
359 if (getSubstring().size() != 2)
360 return emitOpError("substring must contain 2 indices when provided");
361 }
362 if (getComplexPart()) {
363 if (!fir::isa_complex(outputElementType))
364 return emitOpError("memref or component must have complex type if "
365 "complex_part is provided");
366 if (auto firCplx = mlir::dyn_cast<fir::ComplexType>(outputElementType))
367 outputElementType = firCplx.getElementType();
368 else
369 outputElementType =
370 mlir::cast<mlir::ComplexType>(outputElementType).getElementType();
371 }
372 mlir::Type resultBaseType =
373 getFortranElementOrSequenceType(getResult().getType());
374 unsigned resultRank = 0;
375 if (auto resultSeqType = mlir::dyn_cast<fir::SequenceType>(resultBaseType))
376 resultRank = resultSeqType.getDimension();
377 if (resultRank != outputRank)
378 return emitOpError("result type rank is not consistent with operands, "
379 "expected rank ")
380 << outputRank;
381 mlir::Type resultElementType = fir::unwrapSequenceType(resultBaseType);
382 // result type must match the one that was inferred here, except the character
383 // length may differ because of substrings.
384 if (resultElementType != outputElementType &&
385 !(mlir::isa<fir::CharacterType>(resultElementType) &&
386 mlir::isa<fir::CharacterType>(outputElementType)) &&
387 !(mlir::isa<mlir::FloatType>(resultElementType) &&
388 mlir::isa<fir::RealType>(outputElementType)))
389 return emitOpError(
390 "result element type is not consistent with operands, expected ")
391 << outputElementType;
392
393 if (isBoxAddressType(getResult().getType())) {
394 if (!hasBoxComponent || numSubscripts != 0 || !getSubstring().empty() ||
395 getComplexPart())
396 return emitOpError(
397 "result type must only be a box address type if it designates a "
398 "component that is a fir.box or fir.class and if there are no "
399 "indices, substrings, and complex part");
400
401 } else {
402 if ((resultRank == 0) != !getShape())
403 return emitOpError("shape must be provided if and only if the result is "
404 "an array that is not a box address");
405 if (resultRank != 0) {
406 auto shapeType = mlir::dyn_cast<fir::ShapeType>(getShape().getType());
407 auto shapeShiftType =
408 mlir::dyn_cast<fir::ShapeShiftType>(getShape().getType());
409 if (!((shapeType && shapeType.getRank() == resultRank) ||
410 (shapeShiftType && shapeShiftType.getRank() == resultRank)))
411 return emitOpError("shape must be a fir.shape or fir.shapeshift with "
412 "the rank of the result");
413 }
414 auto numLenParam = getTypeparams().size();
415 if (mlir::isa<fir::CharacterType>(outputElementType)) {
416 if (numLenParam != 1)
417 return emitOpError("must be provided one length parameter when the "
418 "result is a character");
419 } else if (fir::isRecordWithTypeParameters(outputElementType)) {
420 if (numLenParam !=
421 mlir::cast<fir::RecordType>(outputElementType).getNumLenParams())
422 return emitOpError("must be provided the same number of length "
423 "parameters as in the result derived type");
424 } else if (numLenParam != 0) {
425 return emitOpError("must not be provided length parameters if the result "
426 "type does not have length parameters");
427 }
428 }
429 return mlir::success();
430 }
431
432 //===----------------------------------------------------------------------===//
433 // ParentComponentOp
434 //===----------------------------------------------------------------------===//
435
436 llvm::LogicalResult hlfir::ParentComponentOp::verify() {
437 mlir::Type baseType =
438 hlfir::getFortranElementOrSequenceType(getMemref().getType());
439 auto maybeInputSeqType = mlir::dyn_cast<fir::SequenceType>(baseType);
440 unsigned inputTypeRank =
441 maybeInputSeqType ? maybeInputSeqType.getDimension() : 0;
442 unsigned shapeRank = 0;
443 if (mlir::Value shape = getShape())
444 if (auto shapeType = mlir::dyn_cast<fir::ShapeType>(shape.getType()))
445 shapeRank = shapeType.getRank();
446 if (inputTypeRank != shapeRank)
447 return emitOpError(
448 "must be provided a shape if and only if the base is an array");
449 mlir::Type outputBaseType = hlfir::getFortranElementOrSequenceType(getType());
450 auto maybeOutputSeqType = mlir::dyn_cast<fir::SequenceType>(outputBaseType);
451 unsigned outputTypeRank =
452 maybeOutputSeqType ? maybeOutputSeqType.getDimension() : 0;
453 if (inputTypeRank != outputTypeRank)
454 return emitOpError("result type rank must match input type rank");
455 if (maybeOutputSeqType && maybeInputSeqType)
456 for (auto [inputDim, outputDim] :
457 llvm::zip(maybeInputSeqType.getShape(), maybeOutputSeqType.getShape()))
458 if (inputDim != fir::SequenceType::getUnknownExtent() &&
459 outputDim != fir::SequenceType::getUnknownExtent())
460 if (inputDim != outputDim)
461 return emitOpError(
462 "result type extents are inconsistent with memref type");
463 fir::RecordType baseRecType =
464 mlir::dyn_cast<fir::RecordType>(hlfir::getFortranElementType(baseType));
465 fir::RecordType outRecType = mlir::dyn_cast<fir::RecordType>(
466 hlfir::getFortranElementType(outputBaseType));
467 if (!baseRecType || !outRecType)
468 return emitOpError("result type and input type must be derived types");
469
470 // Note: result should not be a fir.class: its dynamic type is being set to
471 // the parent type and allowing fir.class would break the operation codegen:
472 // it would keep the input dynamic type.
473 if (mlir::isa<fir::ClassType>(getType()))
474 return emitOpError("result type must not be polymorphic");
475
476 // The array results are known to not be dis-contiguous in most cases (the
477 // exception being if the parent type was extended by a type without any
478 // components): require a fir.box to be used for the result to carry the
479 // strides.
480 if (!mlir::isa<fir::BoxType>(getType()) &&
481 (outputTypeRank != 0 || fir::isRecordWithTypeParameters(outRecType)))
482 return emitOpError("result type must be a fir.box if the result is an "
483 "array or has length parameters");
484 return mlir::success();
485 }
486
487 //===----------------------------------------------------------------------===//
488 // LogicalReductionOp
489 //===----------------------------------------------------------------------===//
490 template <typename LogicalReductionOp>
491 static llvm::LogicalResult
492 verifyLogicalReductionOp(LogicalReductionOp reductionOp) {
493 mlir::Operation *op = reductionOp->getOperation();
494
495 auto results = op->getResultTypes();
496 assert(results.size() == 1);
497
498 mlir::Value mask = reductionOp->getMask();
499 mlir::Value dim = reductionOp->getDim();
500
501 fir::SequenceType maskTy = mlir::cast<fir::SequenceType>(
502 hlfir::getFortranElementOrSequenceType(mask.getType()));
503 mlir::Type logicalTy = maskTy.getEleTy();
504 llvm::ArrayRef<int64_t> maskShape = maskTy.getShape();
505
506 mlir::Type resultType = results[0];
507 if (mlir::isa<fir::LogicalType>(resultType)) {
508 // Result is of the same type as MASK
509 if ((resultType != logicalTy) && useStrictIntrinsicVerifier)
510 return reductionOp->emitOpError(
511 "result must have the same element type as MASK argument");
512
513 } else if (auto resultExpr =
514 mlir::dyn_cast_or_null<hlfir::ExprType>(resultType)) {
515 // Result should only be in hlfir.expr form if it is an array
516 if (maskShape.size() > 1 && dim != nullptr) {
517 if (!resultExpr.isArray())
518 return reductionOp->emitOpError("result must be an array");
519
520 if ((resultExpr.getEleTy() != logicalTy) && useStrictIntrinsicVerifier)
521 return reductionOp->emitOpError(
522 "result must have the same element type as MASK argument");
523
524 llvm::ArrayRef<int64_t> resultShape = resultExpr.getShape();
525 // Result has rank n-1
526 if (resultShape.size() != (maskShape.size() - 1))
527 return reductionOp->emitOpError(
528 "result rank must be one less than MASK");
529 } else {
530 return reductionOp->emitOpError("result must be of logical type");
531 }
532 } else {
533 return reductionOp->emitOpError("result must be of logical type");
534 }
535 return mlir::success();
536 }
537
538 //===----------------------------------------------------------------------===//
539 // AllOp
540 //===----------------------------------------------------------------------===//
541
542 llvm::LogicalResult hlfir::AllOp::verify() {
543 return verifyLogicalReductionOp<hlfir::AllOp *>(this);
544 }
545
546 void hlfir::AllOp::getEffects(
547 llvm::SmallVectorImpl<
548 mlir::SideEffects::EffectInstance<mlir::MemoryEffects::Effect>>
549 &effects) {
550 getIntrinsicEffects(getOperation(), effects);
551 }
552
553 //===----------------------------------------------------------------------===//
554 // AnyOp
555 //===----------------------------------------------------------------------===//
556
557 llvm::LogicalResult hlfir::AnyOp::verify() {
558 return verifyLogicalReductionOp<hlfir::AnyOp *>(this);
559 }
560
561 void hlfir::AnyOp::getEffects(
562 llvm::SmallVectorImpl<
563 mlir::SideEffects::EffectInstance<mlir::MemoryEffects::Effect>>
564 &effects) {
565 getIntrinsicEffects(getOperation(), effects);
566 }
567
568 //===----------------------------------------------------------------------===//
569 // CountOp
570 //===----------------------------------------------------------------------===//
571
572 llvm::LogicalResult hlfir::CountOp::verify() {
573 mlir::Operation *op = getOperation();
574
575 auto results = op->getResultTypes();
576 assert(results.size() == 1);
577 mlir::Value mask = getMask();
578 mlir::Value dim = getDim();
579
580 fir::SequenceType maskTy = mlir::cast<fir::SequenceType>(
581 hlfir::getFortranElementOrSequenceType(mask.getType()));
582 llvm::ArrayRef<int64_t> maskShape = maskTy.getShape();
583
584 mlir::Type resultType = results[0];
585 if (auto resultExpr = mlir::dyn_cast_or_null<hlfir::ExprType>(resultType)) {
586 if (maskShape.size() > 1 && dim != nullptr) {
587 if (!resultExpr.isArray())
588 return emitOpError("result must be an array");
589
590 llvm::ArrayRef<int64_t> resultShape = resultExpr.getShape();
591 // Result has rank n-1
592 if (resultShape.size() != (maskShape.size() - 1))
593 return emitOpError("result rank must be one less than MASK");
594 } else {
595 return emitOpError("result must be of numerical array type");
596 }
597 } else if (!hlfir::isFortranScalarNumericalType(resultType)) {
598 return emitOpError("result must be of numerical scalar type");
599 }
600
601 return mlir::success();
602 }
603
604 void hlfir::CountOp::getEffects(
605 llvm::SmallVectorImpl<
606 mlir::SideEffects::EffectInstance<mlir::MemoryEffects::Effect>>
607 &effects) {
608 getIntrinsicEffects(getOperation(), effects);
609 }
610
611 //===----------------------------------------------------------------------===//
612 // ConcatOp
613 //===----------------------------------------------------------------------===//
614
615 static unsigned getCharacterKind(mlir::Type t) {
616 return mlir::cast<fir::CharacterType>(hlfir::getFortranElementType(t))
617 .getFKind();
618 }
619
620 static std::optional<fir::CharacterType::LenType>
621 getCharacterLengthIfStatic(mlir::Type t) {
622 if (auto charType =
623 mlir::dyn_cast<fir::CharacterType>(hlfir::getFortranElementType(t)))
624 if (charType.hasConstantLen())
625 return charType.getLen();
626 return std::nullopt;
627 }
628
629 llvm::LogicalResult hlfir::ConcatOp::verify() {
630 if (getStrings().size() < 2)
631 return emitOpError("must be provided at least two string operands");
632 unsigned kind = getCharacterKind(getResult().getType());
633 for (auto string : getStrings())
634 if (kind != getCharacterKind(string.getType()))
635 return emitOpError("strings must have the same KIND as the result type");
636 return mlir::success();
637 }
638
639 void hlfir::ConcatOp::build(mlir::OpBuilder &builder,
640 mlir::OperationState &result,
641 mlir::ValueRange strings, mlir::Value len) {
642 fir::CharacterType::LenType resultTypeLen = 0;
643 assert(!strings.empty() && "must contain operands");
644 unsigned kind = getCharacterKind(strings[0].getType());
645 for (auto string : strings)
646 if (auto cstLen = getCharacterLengthIfStatic(string.getType())) {
647 resultTypeLen += *cstLen;
648 } else {
649 resultTypeLen = fir::CharacterType::unknownLen();
650 break;
651 }
652 auto resultType = hlfir::ExprType::get(
653 builder.getContext(), hlfir::ExprType::Shape{},
654 fir::CharacterType::get(builder.getContext(), kind, resultTypeLen),
655 false);
656 build(builder, result, resultType, strings, len);
657 }
658
659 void hlfir::ConcatOp::getEffects(
660 llvm::SmallVectorImpl<
661 mlir::SideEffects::EffectInstance<mlir::MemoryEffects::Effect>>
662 &effects) {
663 getIntrinsicEffects(getOperation(), effects);
664 }
665
666 //===----------------------------------------------------------------------===//
667 // NumericalReductionOp
668 //===----------------------------------------------------------------------===//
669
670 template <typename NumericalReductionOp>
671 static llvm::LogicalResult
672 verifyArrayAndMaskForReductionOp(NumericalReductionOp reductionOp) {
673 mlir::Value array = reductionOp->getArray();
674 mlir::Value mask = reductionOp->getMask();
675
676 fir::SequenceType arrayTy = mlir::cast<fir::SequenceType>(
677 hlfir::getFortranElementOrSequenceType(array.getType()));
678 llvm::ArrayRef<int64_t> arrayShape = arrayTy.getShape();
679
680 if (mask) {
681 fir::SequenceType maskSeq = mlir::dyn_cast<fir::SequenceType>(
682 hlfir::getFortranElementOrSequenceType(mask.getType()));
683 llvm::ArrayRef<int64_t> maskShape;
684
685 if (maskSeq)
686 maskShape = maskSeq.getShape();
687
688 if (!maskShape.empty()) {
689 if (maskShape.size() != arrayShape.size())
690 return reductionOp->emitWarning("MASK must be conformable to ARRAY");
691 if (useStrictIntrinsicVerifier) {
692 static_assert(fir::SequenceType::getUnknownExtent() ==
693 hlfir::ExprType::getUnknownExtent());
694 constexpr int64_t unknownExtent = fir::SequenceType::getUnknownExtent();
695 for (std::size_t i = 0; i < arrayShape.size(); ++i) {
696 int64_t arrayExtent = arrayShape[i];
697 int64_t maskExtent = maskShape[i];
698 if ((arrayExtent != maskExtent) && (arrayExtent != unknownExtent) &&
699 (maskExtent != unknownExtent))
700 return reductionOp->emitWarning(
701 "MASK must be conformable to ARRAY");
702 }
703 }
704 }
705 }
706 return mlir::success();
707 }
708
709 template <typename NumericalReductionOp>
710 static llvm::LogicalResult
711 verifyNumericalReductionOp(NumericalReductionOp reductionOp) {
712 mlir::Operation *op = reductionOp->getOperation();
713 auto results = op->getResultTypes();
714 assert(results.size() == 1);
715
716 auto res = verifyArrayAndMaskForReductionOp(reductionOp);
717 if (failed(res))
718 return res;
719
720 mlir::Value array = reductionOp->getArray();
721 mlir::Value dim = reductionOp->getDim();
722 fir::SequenceType arrayTy = mlir::cast<fir::SequenceType>(
723 hlfir::getFortranElementOrSequenceType(array.getType()));
724 mlir::Type numTy = arrayTy.getEleTy();
725 llvm::ArrayRef<int64_t> arrayShape = arrayTy.getShape();
726
727 mlir::Type resultType = results[0];
728 if (hlfir::isFortranScalarNumericalType(resultType)) {
729 // Result is of the same type as ARRAY
730 if ((resultType != numTy) && useStrictIntrinsicVerifier)
731 return reductionOp->emitOpError(
732 "result must have the same element type as ARRAY argument");
733
734 } else if (auto resultExpr =
735 mlir::dyn_cast_or_null<hlfir::ExprType>(resultType)) {
736 if (arrayShape.size() > 1 && dim != nullptr) {
737 if (!resultExpr.isArray())
738 return reductionOp->emitOpError("result must be an array");
739
740 if ((resultExpr.getEleTy() != numTy) && useStrictIntrinsicVerifier)
741 return reductionOp->emitOpError(
742 "result must have the same element type as ARRAY argument");
743
744 llvm::ArrayRef<int64_t> resultShape = resultExpr.getShape();
745 // Result has rank n-1
746 if (resultShape.size() != (arrayShape.size() - 1))
747 return reductionOp->emitOpError(
748 "result rank must be one less than ARRAY");
749 } else {
750 return reductionOp->emitOpError(
751 "result must be of numerical scalar type");
752 }
753 } else {
754 return reductionOp->emitOpError("result must be of numerical scalar type");
755 }
756 return mlir::success();
757 }
758
759 //===----------------------------------------------------------------------===//
760 // ProductOp
761 //===----------------------------------------------------------------------===//
762
763 llvm::LogicalResult hlfir::ProductOp::verify() {
764 return verifyNumericalReductionOp<hlfir::ProductOp *>(this);
765 }
766
767 void hlfir::ProductOp::getEffects(
768 llvm::SmallVectorImpl<
769 mlir::SideEffects::EffectInstance<mlir::MemoryEffects::Effect>>
770 &effects) {
771 getIntrinsicEffects(getOperation(), effects);
772 }
773
774 //===----------------------------------------------------------------------===//
775 // CharacterReductionOp
776 //===----------------------------------------------------------------------===//
777
778 template <typename CharacterReductionOp>
779 static llvm::LogicalResult
780 verifyCharacterReductionOp(CharacterReductionOp reductionOp) {
781 mlir::Operation *op = reductionOp->getOperation();
782 auto results = op->getResultTypes();
783 assert(results.size() == 1);
784
785 auto res = verifyArrayAndMaskForReductionOp(reductionOp);
786 if (failed(res))
787 return res;
788
789 mlir::Value array = reductionOp->getArray();
790 mlir::Value dim = reductionOp->getDim();
791 fir::SequenceType arrayTy = mlir::cast<fir::SequenceType>(
792 hlfir::getFortranElementOrSequenceType(array.getType()));
793 mlir::Type numTy = arrayTy.getEleTy();
794 llvm::ArrayRef<int64_t> arrayShape = arrayTy.getShape();
795
796 auto resultExpr = mlir::cast<hlfir::ExprType>(results[0]);
797 mlir::Type resultType = resultExpr.getEleTy();
798 assert(mlir::isa<fir::CharacterType>(resultType) &&
799 "result must be character");
800
801 // Result is of the same type as ARRAY
802 if ((resultType != numTy) && useStrictIntrinsicVerifier)
803 return reductionOp->emitOpError(
804 "result must have the same element type as ARRAY argument");
805
806 if (arrayShape.size() > 1 && dim != nullptr) {
807 if (!resultExpr.isArray())
808 return reductionOp->emitOpError("result must be an array");
809 llvm::ArrayRef<int64_t> resultShape = resultExpr.getShape();
810 // Result has rank n-1
811 if (resultShape.size() != (arrayShape.size() - 1))
812 return reductionOp->emitOpError(
813 "result rank must be one less than ARRAY");
814 } else if (!resultExpr.isScalar()) {
815 return reductionOp->emitOpError("result must be scalar character");
816 }
817 return mlir::success();
818 }
819
820 //===----------------------------------------------------------------------===//
821 // MaxvalOp
822 //===----------------------------------------------------------------------===//
823
824 llvm::LogicalResult hlfir::MaxvalOp::verify() {
825 mlir::Operation *op = getOperation();
826
827 auto results = op->getResultTypes();
828 assert(results.size() == 1);
829
830 auto resultExpr = mlir::dyn_cast<hlfir::ExprType>(results[0]);
831 if (resultExpr && mlir::isa<fir::CharacterType>(resultExpr.getEleTy())) {
832 return verifyCharacterReductionOp<hlfir::MaxvalOp *>(this);
833 }
834 return verifyNumericalReductionOp<hlfir::MaxvalOp *>(this);
835 }
836
837 void hlfir::MaxvalOp::getEffects(
838 llvm::SmallVectorImpl<
839 mlir::SideEffects::EffectInstance<mlir::MemoryEffects::Effect>>
840 &effects) {
841 getIntrinsicEffects(getOperation(), effects);
842 }
843
844 //===----------------------------------------------------------------------===//
845 // MinvalOp
846 //===----------------------------------------------------------------------===//
847
848 llvm::LogicalResult hlfir::MinvalOp::verify() {
849 mlir::Operation *op = getOperation();
850
851 auto results = op->getResultTypes();
852 assert(results.size() == 1);
853
854 auto resultExpr = mlir::dyn_cast<hlfir::ExprType>(results[0]);
855 if (resultExpr && mlir::isa<fir::CharacterType>(resultExpr.getEleTy())) {
856 return verifyCharacterReductionOp<hlfir::MinvalOp *>(this);
857 }
858 return verifyNumericalReductionOp<hlfir::MinvalOp *>(this);
859 }
860
861 void hlfir::MinvalOp::getEffects(
862 llvm::SmallVectorImpl<
863 mlir::SideEffects::EffectInstance<mlir::MemoryEffects::Effect>>
864 &effects) {
865 getIntrinsicEffects(getOperation(), effects);
866 }
867
868 //===----------------------------------------------------------------------===//
869 // MinlocOp
870 //===----------------------------------------------------------------------===//
871
872 template <typename NumericalReductionOp>
873 static llvm::LogicalResult
874 verifyResultForMinMaxLoc(NumericalReductionOp reductionOp) {
875 mlir::Operation *op = reductionOp->getOperation();
876 auto results = op->getResultTypes();
877 assert(results.size() == 1);
878
879 mlir::Value array = reductionOp->getArray();
880 mlir::Value dim = reductionOp->getDim();
881 fir::SequenceType arrayTy = mlir::cast<fir::SequenceType>(
882 hlfir::getFortranElementOrSequenceType(array.getType()));
883 llvm::ArrayRef<int64_t> arrayShape = arrayTy.getShape();
884
885 mlir::Type resultType = results[0];
886 if (dim && arrayShape.size() == 1) {
887 if (!fir::isa_integer(resultType))
888 return reductionOp->emitOpError("result must be scalar integer");
889 } else if (auto resultExpr =
890 mlir::dyn_cast_or_null<hlfir::ExprType>(resultType)) {
891 if (!resultExpr.isArray())
892 return reductionOp->emitOpError("result must be an array");
893
894 if (!fir::isa_integer(resultExpr.getEleTy()))
895 return reductionOp->emitOpError("result must have integer elements");
896
897 llvm::ArrayRef<int64_t> resultShape = resultExpr.getShape();
898 // With dim the result has rank n-1
899 if (dim && resultShape.size() != (arrayShape.size() - 1))
900 return reductionOp->emitOpError(
901 "result rank must be one less than ARRAY");
902 // With dim the result has rank n
903 if (!dim && resultShape.size() != 1)
904 return reductionOp->emitOpError("result rank must be 1");
905 } else {
906 return reductionOp->emitOpError("result must be of numerical expr type");
907 }
908 return mlir::success();
909 }
910
911 llvm::LogicalResult hlfir::MinlocOp::verify() {
912 auto res = verifyArrayAndMaskForReductionOp(this);
913 if (failed(res))
914 return res;
915
916 return verifyResultForMinMaxLoc(this);
917 }
918
919 void hlfir::MinlocOp::getEffects(
920 llvm::SmallVectorImpl<
921 mlir::SideEffects::EffectInstance<mlir::MemoryEffects::Effect>>
922 &effects) {
923 getIntrinsicEffects(getOperation(), effects);
924 }
925
926 //===----------------------------------------------------------------------===//
927 // MaxlocOp
928 //===----------------------------------------------------------------------===//
929
930 llvm::LogicalResult hlfir::MaxlocOp::verify() {
931 auto res = verifyArrayAndMaskForReductionOp(this);
932 if (failed(res))
933 return res;
934
935 return verifyResultForMinMaxLoc(this);
936 }
937
938 void hlfir::MaxlocOp::getEffects(
939 llvm::SmallVectorImpl<
940 mlir::SideEffects::EffectInstance<mlir::MemoryEffects::Effect>>
941 &effects) {
942 getIntrinsicEffects(getOperation(), effects);
943 }
944
945 //===----------------------------------------------------------------------===//
946 // SetLengthOp
947 //===----------------------------------------------------------------------===//
948
949 void hlfir::SetLengthOp::build(mlir::OpBuilder &builder,
950 mlir::OperationState &result, mlir::Value string,
951 mlir::Value len) {
952 fir::CharacterType::LenType resultTypeLen = fir::CharacterType::unknownLen();
953 if (auto cstLen = fir::getIntIfConstant(len))
954 resultTypeLen = *cstLen;
955 unsigned kind = getCharacterKind(string.getType());
956 auto resultType = hlfir::ExprType::get(
957 builder.getContext(), hlfir::ExprType::Shape{},
958 fir::CharacterType::get(builder.getContext(), kind, resultTypeLen),
959 false);
960 build(builder, result, resultType, string, len);
961 }
962
963 void hlfir::SetLengthOp::getEffects(
964 llvm::SmallVectorImpl<
965 mlir::SideEffects::EffectInstance<mlir::MemoryEffects::Effect>>
966 &effects) {
967 getIntrinsicEffects(getOperation(), effects);
968 }
969
970 //===----------------------------------------------------------------------===//
971 // SumOp
972 //===----------------------------------------------------------------------===//
973
974 llvm::LogicalResult hlfir::SumOp::verify() {
975 return verifyNumericalReductionOp<hlfir::SumOp *>(this);
976 }
977
978 void hlfir::SumOp::getEffects(
979 llvm::SmallVectorImpl<
980 mlir::SideEffects::EffectInstance<mlir::MemoryEffects::Effect>>
981 &effects) {
982 getIntrinsicEffects(getOperation(), effects);
983 }
984
985 //===----------------------------------------------------------------------===//
986 // DotProductOp
987 //===----------------------------------------------------------------------===//
988
989 llvm::LogicalResult hlfir::DotProductOp::verify() {
990 mlir::Value lhs = getLhs();
991 mlir::Value rhs = getRhs();
992 fir::SequenceType lhsTy = mlir::cast<fir::SequenceType>(
993 hlfir::getFortranElementOrSequenceType(lhs.getType()));
994 fir::SequenceType rhsTy = mlir::cast<fir::SequenceType>(
995 hlfir::getFortranElementOrSequenceType(rhs.getType()));
996 llvm::ArrayRef<int64_t> lhsShape = lhsTy.getShape();
997 llvm::ArrayRef<int64_t> rhsShape = rhsTy.getShape();
998 std::size_t lhsRank = lhsShape.size();
999 std::size_t rhsRank = rhsShape.size();
1000 mlir::Type lhsEleTy = lhsTy.getEleTy();
1001 mlir::Type rhsEleTy = rhsTy.getEleTy();
1002 mlir::Type resultTy = getResult().getType();
1003
1004 if ((lhsRank != 1) || (rhsRank != 1))
1005 return emitOpError("both arrays must have rank 1");
1006
1007 int64_t lhsSize = lhsShape[0];
1008 int64_t rhsSize = rhsShape[0];
1009
1010 constexpr int64_t unknownExtent = fir::SequenceType::getUnknownExtent();
1011 if ((lhsSize != unknownExtent) && (rhsSize != unknownExtent) &&
1012 (lhsSize != rhsSize) && useStrictIntrinsicVerifier)
1013 return emitOpError("both arrays must have the same size");
1014
1015 if (useStrictIntrinsicVerifier) {
1016 if (mlir::isa<fir::LogicalType>(lhsEleTy) !=
1017 mlir::isa<fir::LogicalType>(rhsEleTy))
1018 return emitOpError("if one array is logical, so should the other be");
1019
1020 if (mlir::isa<fir::LogicalType>(lhsEleTy) !=
1021 mlir::isa<fir::LogicalType>(resultTy))
1022 return emitOpError("the result type should be a logical only if the "
1023 "argument types are logical");
1024 }
1025
1026 if (!hlfir::isFortranScalarNumericalType(resultTy) &&
1027 !mlir::isa<fir::LogicalType>(resultTy))
1028 return emitOpError(
1029 "the result must be of scalar numerical or logical type");
1030
1031 return mlir::success();
1032 }
1033
1034 void hlfir::DotProductOp::getEffects(
1035 llvm::SmallVectorImpl<
1036 mlir::SideEffects::EffectInstance<mlir::MemoryEffects::Effect>>
1037 &effects) {
1038 getIntrinsicEffects(getOperation(), effects);
1039 }
1040
1041 //===----------------------------------------------------------------------===//
1042 // MatmulOp
1043 //===----------------------------------------------------------------------===//
1044
1045 llvm::LogicalResult hlfir::MatmulOp::verify() {
1046 mlir::Value lhs = getLhs();
1047 mlir::Value rhs = getRhs();
1048 fir::SequenceType lhsTy = mlir::cast<fir::SequenceType>(
1049 hlfir::getFortranElementOrSequenceType(lhs.getType()));
1050 fir::SequenceType rhsTy = mlir::cast<fir::SequenceType>(
1051 hlfir::getFortranElementOrSequenceType(rhs.getType()));
1052 llvm::ArrayRef<int64_t> lhsShape = lhsTy.getShape();
1053 llvm::ArrayRef<int64_t> rhsShape = rhsTy.getShape();
1054 std::size_t lhsRank = lhsShape.size();
1055 std::size_t rhsRank = rhsShape.size();
1056 mlir::Type lhsEleTy = lhsTy.getEleTy();
1057 mlir::Type rhsEleTy = rhsTy.getEleTy();
1058 hlfir::ExprType resultTy = mlir::cast<hlfir::ExprType>(getResult().getType());
1059 llvm::ArrayRef<int64_t> resultShape = resultTy.getShape();
1060 mlir::Type resultEleTy = resultTy.getEleTy();
1061
1062 if (((lhsRank != 1) && (lhsRank != 2)) || ((rhsRank != 1) && (rhsRank != 2)))
1063 return emitOpError("array must have either rank 1 or rank 2");
1064
1065 if ((lhsRank == 1) && (rhsRank == 1))
1066 return emitOpError("at least one array must have rank 2");
1067
1068 if (mlir::isa<fir::LogicalType>(lhsEleTy) !=
1069 mlir::isa<fir::LogicalType>(rhsEleTy))
1070 return emitOpError("if one array is logical, so should the other be");
1071
1072 if (!useStrictIntrinsicVerifier)
1073 return mlir::success();
1074
1075 int64_t lastLhsDim = lhsShape[lhsRank - 1];
1076 int64_t firstRhsDim = rhsShape[0];
1077 constexpr int64_t unknownExtent = fir::SequenceType::getUnknownExtent();
1078 if (lastLhsDim != firstRhsDim)
1079 if ((lastLhsDim != unknownExtent) && (firstRhsDim != unknownExtent))
1080 return emitOpError(
1081 "the last dimension of LHS should match the first dimension of RHS");
1082
1083 if (mlir::isa<fir::LogicalType>(lhsEleTy) !=
1084 mlir::isa<fir::LogicalType>(resultEleTy))
1085 return emitOpError("the result type should be a logical only if the "
1086 "argument types are logical");
1087
1088 llvm::SmallVector<int64_t, 2> expectedResultShape;
1089 if (lhsRank == 2) {
1090 if (rhsRank == 2) {
1091 expectedResultShape.push_back(lhsShape[0]);
1092 expectedResultShape.push_back(rhsShape[1]);
1093 } else {
1094 // rhsRank == 1
1095 expectedResultShape.push_back(lhsShape[0]);
1096 }
1097 } else {
1098 // lhsRank == 1
1099 // rhsRank == 2
1100 expectedResultShape.push_back(rhsShape[1]);
1101 }
1102 if (resultShape.size() != expectedResultShape.size())
1103 return emitOpError("incorrect result shape");
1104 if (resultShape[0] != expectedResultShape[0] &&
1105 expectedResultShape[0] != unknownExtent)
1106 return emitOpError("incorrect result shape");
1107 if (resultShape.size() == 2 && resultShape[1] != expectedResultShape[1] &&
1108 expectedResultShape[1] != unknownExtent)
1109 return emitOpError("incorrect result shape");
1110
1111 return mlir::success();
1112 }
1113
1114 llvm::LogicalResult
1115 hlfir::MatmulOp::canonicalize(MatmulOp matmulOp,
1116 mlir::PatternRewriter &rewriter) {
1117 // the only two uses of the transposed matrix should be for the hlfir.matmul
1118 // and hlfir.destroy
1119 auto isOtherwiseUnused = [&](hlfir::TransposeOp transposeOp) -> bool {
1120 std::size_t numUses = 0;
1121 for (mlir::Operation *user : transposeOp.getResult().getUsers()) {
1122 ++numUses;
1123 if (user == matmulOp)
1124 continue;
1125 if (mlir::dyn_cast_or_null<hlfir::DestroyOp>(user))
1126 continue;
1127 // some other use!
1128 return false;
1129 }
1130 return numUses <= 2;
1131 };
1132
1133 mlir::Value lhs = matmulOp.getLhs();
1134 // Rewrite MATMUL(TRANSPOSE(lhs), rhs) => hlfir.matmul_transpose lhs, rhs
1135 if (auto transposeOp = lhs.getDefiningOp<hlfir::TransposeOp>()) {
1136 if (isOtherwiseUnused(transposeOp)) {
1137 mlir::Location loc = matmulOp.getLoc();
1138 mlir::Type resultTy = matmulOp.getResult().getType();
1139 auto matmulTransposeOp = rewriter.create<hlfir::MatmulTransposeOp>(
1140 loc, resultTy, transposeOp.getArray(), matmulOp.getRhs());
1141
1142 // we don't need to remove any hlfir.destroy because it will be needed for
1143 // the new intrinsic result anyway
1144 rewriter.replaceOp(matmulOp, matmulTransposeOp.getResult());
1145
1146 // but we do need to get rid of the hlfir.destroy for the hlfir.transpose
1147 // result (which is entirely removed)
1148 llvm::SmallVector<mlir::Operation *> users(
1149 transposeOp->getResult(0).getUsers());
1150 for (mlir::Operation *user : users)
1151 if (auto destroyOp = mlir::dyn_cast_or_null<hlfir::DestroyOp>(user))
1152 rewriter.eraseOp(destroyOp);
1153 rewriter.eraseOp(transposeOp);
1154
1155 return mlir::success();
1156 }
1157 }
1158
1159 return mlir::failure();
1160 }
1161
1162 void hlfir::MatmulOp::getEffects(
1163 llvm::SmallVectorImpl<
1164 mlir::SideEffects::EffectInstance<mlir::MemoryEffects::Effect>>
1165 &effects) {
1166 getIntrinsicEffects(getOperation(), effects);
1167 }
1168
1169 //===----------------------------------------------------------------------===//
1170 // TransposeOp
1171 //===----------------------------------------------------------------------===//
1172
1173 llvm::LogicalResult hlfir::TransposeOp::verify() {
1174 mlir::Value array = getArray();
1175 fir::SequenceType arrayTy = mlir::cast<fir::SequenceType>(
1176 hlfir::getFortranElementOrSequenceType(array.getType()));
1177 llvm::ArrayRef<int64_t> inShape = arrayTy.getShape();
1178 std::size_t rank = inShape.size();
1179 mlir::Type eleTy = arrayTy.getEleTy();
1180 hlfir::ExprType resultTy = mlir::cast<hlfir::ExprType>(getResult().getType());
1181 llvm::ArrayRef<int64_t> resultShape = resultTy.getShape();
1182 std::size_t resultRank = resultShape.size();
1183 mlir::Type resultEleTy = resultTy.getEleTy();
1184
1185 if (rank != 2 || resultRank != 2)
1186 return emitOpError("input and output arrays should have rank 2");
1187
1188 if (!useStrictIntrinsicVerifier)
1189 return mlir::success();
1190
1191 constexpr int64_t unknownExtent = fir::SequenceType::getUnknownExtent();
1192 if ((inShape[0] != resultShape[1]) && (inShape[0] != unknownExtent))
1193 return emitOpError("output shape does not match input array");
1194 if ((inShape[1] != resultShape[0]) && (inShape[1] != unknownExtent))
1195 return emitOpError("output shape does not match input array");
1196
1197 if (eleTy != resultEleTy)
1198 return emitOpError(
1199 "input and output arrays should have the same element type");
1200
1201 return mlir::success();
1202 }
1203
1204 void hlfir::TransposeOp::getEffects(
1205 llvm::SmallVectorImpl<
1206 mlir::SideEffects::EffectInstance<mlir::MemoryEffects::Effect>>
1207 &effects) {
1208 getIntrinsicEffects(getOperation(), effects);
1209 }
1210
1211 //===----------------------------------------------------------------------===//
1212 // MatmulTransposeOp
1213 //===----------------------------------------------------------------------===//
1214
1215 llvm::LogicalResult hlfir::MatmulTransposeOp::verify() {
1216 mlir::Value lhs = getLhs();
1217 mlir::Value rhs = getRhs();
1218 fir::SequenceType lhsTy = mlir::cast<fir::SequenceType>(
1219 hlfir::getFortranElementOrSequenceType(lhs.getType()));
1220 fir::SequenceType rhsTy = mlir::cast<fir::SequenceType>(
1221 hlfir::getFortranElementOrSequenceType(rhs.getType()));
1222 llvm::ArrayRef<int64_t> lhsShape = lhsTy.getShape();
1223 llvm::ArrayRef<int64_t> rhsShape = rhsTy.getShape();
1224 std::size_t lhsRank = lhsShape.size();
1225 std::size_t rhsRank = rhsShape.size();
1226 mlir::Type lhsEleTy = lhsTy.getEleTy();
1227 mlir::Type rhsEleTy = rhsTy.getEleTy();
1228 hlfir::ExprType resultTy = mlir::cast<hlfir::ExprType>(getResult().getType());
1229 llvm::ArrayRef<int64_t> resultShape = resultTy.getShape();
1230 mlir::Type resultEleTy = resultTy.getEleTy();
1231
1232 // lhs must have rank 2 for the transpose to be valid
1233 if ((lhsRank != 2) || ((rhsRank != 1) && (rhsRank != 2)))
1234 return emitOpError("array must have either rank 1 or rank 2");
1235
1236 if (!useStrictIntrinsicVerifier)
1237 return mlir::success();
1238
1239 if (mlir::isa<fir::LogicalType>(lhsEleTy) !=
1240 mlir::isa<fir::LogicalType>(rhsEleTy))
1241 return emitOpError("if one array is logical, so should the other be");
1242
1243 // for matmul we compare the last dimension of lhs with the first dimension of
1244 // rhs, but for MatmulTranspose, dimensions of lhs are inverted by the
1245 // transpose
1246 int64_t firstLhsDim = lhsShape[0];
1247 int64_t firstRhsDim = rhsShape[0];
1248 constexpr int64_t unknownExtent = fir::SequenceType::getUnknownExtent();
1249 if (firstLhsDim != firstRhsDim)
1250 if ((firstLhsDim != unknownExtent) && (firstRhsDim != unknownExtent))
1251 return emitOpError(
1252 "the first dimension of LHS should match the first dimension of RHS");
1253
1254 if (mlir::isa<fir::LogicalType>(lhsEleTy) !=
1255 mlir::isa<fir::LogicalType>(resultEleTy))
1256 return emitOpError("the result type should be a logical only if the "
1257 "argument types are logical");
1258
1259 llvm::SmallVector<int64_t, 2> expectedResultShape;
1260 if (rhsRank == 2) {
1261 expectedResultShape.push_back(lhsShape[1]);
1262 expectedResultShape.push_back(rhsShape[1]);
1263 } else {
1264 // rhsRank == 1
1265 expectedResultShape.push_back(lhsShape[1]);
1266 }
1267 if (resultShape.size() != expectedResultShape.size())
1268 return emitOpError("incorrect result shape");
1269 if (resultShape[0] != expectedResultShape[0])
1270 return emitOpError("incorrect result shape");
1271 if (resultShape.size() == 2 && resultShape[1] != expectedResultShape[1])
1272 return emitOpError("incorrect result shape");
1273
1274 return mlir::success();
1275 }
1276
1277 void hlfir::MatmulTransposeOp::getEffects(
1278 llvm::SmallVectorImpl<
1279 mlir::SideEffects::EffectInstance<mlir::MemoryEffects::Effect>>
1280 &effects) {
1281 getIntrinsicEffects(getOperation(), effects);
1282 }
1283
1284 //===----------------------------------------------------------------------===//
1285 // AssociateOp
1286 //===----------------------------------------------------------------------===//
1287
1288 void hlfir::AssociateOp::build(mlir::OpBuilder &builder,
1289 mlir::OperationState &result, mlir::Value source,
1290 llvm::StringRef uniq_name, mlir::Value shape,
1291 mlir::ValueRange typeparams,
1292 fir::FortranVariableFlagsAttr fortran_attrs) {
1293 auto nameAttr = builder.getStringAttr(uniq_name);
1294 mlir::Type dataType = getFortranElementOrSequenceType(source.getType());
1295
1296 // Preserve polymorphism of polymorphic expr.
1297 mlir::Type firVarType;
1298 auto sourceExprType = mlir::dyn_cast<hlfir::ExprType>(source.getType());
1299 if (sourceExprType && sourceExprType.isPolymorphic())
1300 firVarType = fir::ClassType::get(fir::HeapType::get(dataType));
1301 else
1302 firVarType = fir::ReferenceType::get(dataType);
1303
1304 mlir::Type hlfirVariableType =
1305 DeclareOp::getHLFIRVariableType(firVarType, /*hasExplicitLbs=*/false);
1306 mlir::Type i1Type = builder.getI1Type();
1307 build(builder, result, {hlfirVariableType, firVarType, i1Type}, source, shape,
1308 typeparams, nameAttr, fortran_attrs);
1309 }
1310
1311 void hlfir::AssociateOp::build(
1312 mlir::OpBuilder &builder, mlir::OperationState &result, mlir::Value source,
1313 mlir::Value shape, mlir::ValueRange typeparams,
1314 fir::FortranVariableFlagsAttr fortran_attrs,
1315 llvm::ArrayRef<mlir::NamedAttribute> attributes) {
1316 mlir::Type dataType = getFortranElementOrSequenceType(source.getType());
1317
1318 // Preserve polymorphism of polymorphic expr.
1319 mlir::Type firVarType;
1320 auto sourceExprType = mlir::dyn_cast<hlfir::ExprType>(source.getType());
1321 if (sourceExprType && sourceExprType.isPolymorphic())
1322 firVarType = fir::ClassType::get(fir::HeapType::get(dataType));
1323 else
1324 firVarType = fir::ReferenceType::get(dataType);
1325
1326 mlir::Type hlfirVariableType =
1327 DeclareOp::getHLFIRVariableType(firVarType, /*hasExplicitLbs=*/false);
1328 mlir::Type i1Type = builder.getI1Type();
1329 build(builder, result, {hlfirVariableType, firVarType, i1Type}, source, shape,
1330 typeparams, {}, fortran_attrs);
1331 result.addAttributes(attributes);
1332 }
1333
1334 //===----------------------------------------------------------------------===//
1335 // EndAssociateOp
1336 //===----------------------------------------------------------------------===//
1337
1338 void hlfir::EndAssociateOp::build(mlir::OpBuilder &builder,
1339 mlir::OperationState &result,
1340 hlfir::AssociateOp associate) {
1341 mlir::Value hlfirBase = associate.getBase();
1342 mlir::Value firBase = associate.getFirBase();
1343 // If EndAssociateOp may need to initiate the deallocation
1344 // of allocatable components, it has to have access to the variable
1345 // definition, so we cannot use the FIR base as the operand.
1346 return build(builder, result,
1347 hlfir::mayHaveAllocatableComponent(hlfirBase.getType())
1348 ? hlfirBase
1349 : firBase,
1350 associate.getMustFreeStrorageFlag());
1351 }
1352
1353 llvm::LogicalResult hlfir::EndAssociateOp::verify() {
1354 mlir::Value var = getVar();
1355 if (hlfir::mayHaveAllocatableComponent(var.getType()) &&
1356 !hlfir::isFortranEntity(var))
1357 return emitOpError("that requires components deallocation must have var "
1358 "operand that is a Fortran entity");
1359
1360 return mlir::success();
1361 }
1362
1363 //===----------------------------------------------------------------------===//
1364 // AsExprOp
1365 //===----------------------------------------------------------------------===//
1366
1367 void hlfir::AsExprOp::build(mlir::OpBuilder &builder,
1368 mlir::OperationState &result, mlir::Value var,
1369 mlir::Value mustFree) {
1370 hlfir::ExprType::Shape typeShape;
1371 bool isPolymorphic = fir::isPolymorphicType(var.getType());
1372 mlir::Type type = getFortranElementOrSequenceType(var.getType());
1373 if (auto seqType = mlir::dyn_cast<fir::SequenceType>(type)) {
1374 typeShape.append(seqType.getShape().begin(), seqType.getShape().end());
1375 type = seqType.getEleTy();
1376 }
1377
1378 auto resultType = hlfir::ExprType::get(builder.getContext(), typeShape, type,
1379 isPolymorphic);
1380 return build(builder, result, resultType, var, mustFree);
1381 }
1382
1383 void hlfir::AsExprOp::getEffects(
1384 llvm::SmallVectorImpl<
1385 mlir::SideEffects::EffectInstance<mlir::MemoryEffects::Effect>>
1386 &effects) {
1387 // this isn't a transformational intrinsic but follows the same pattern: it
1388 // creates a hlfir.expr and so needs to have an allocation effect, plus it
1389 // might have a pointer-like argument, in which case it has a read effect
1390 // upon those
1391 getIntrinsicEffects(getOperation(), effects);
1392 }
1393
1394 //===----------------------------------------------------------------------===//
1395 // ElementalOp
1396 //===----------------------------------------------------------------------===//
1397
1398 /// Common builder for ElementalOp and ElementalAddrOp to add the arguments and
1399 /// create the elemental body. Result and clean-up body must be handled in
1400 /// specific builders.
1401 template <typename Op>
1402 static void buildElemental(mlir::OpBuilder &builder,
1403 mlir::OperationState &odsState, mlir::Value shape,
1404 mlir::Value mold, mlir::ValueRange typeparams,
1405 bool isUnordered) {
1406 odsState.addOperands(shape);
1407 if (mold)
1408 odsState.addOperands(mold);
1409 odsState.addOperands(typeparams);
1410 odsState.addAttribute(
1411 Op::getOperandSegmentSizesAttrName(odsState.name),
1412 builder.getDenseI32ArrayAttr({/*shape=*/1, (mold ? 1 : 0),
1413 static_cast<int32_t>(typeparams.size())}));
1414 if (isUnordered)
1415 odsState.addAttribute(Op::getUnorderedAttrName(odsState.name),
1416 isUnordered ? builder.getUnitAttr() : nullptr);
1417 mlir::Region *bodyRegion = odsState.addRegion();
1418 bodyRegion->push_back(new mlir::Block{});
1419 if (auto shapeType = mlir::dyn_cast<fir::ShapeType>(shape.getType())) {
1420 unsigned dim = shapeType.getRank();
1421 mlir::Type indexType = builder.getIndexType();
1422 for (unsigned d = 0; d < dim; ++d)
1423 bodyRegion->front().addArgument(indexType, odsState.location);
1424 }
1425 }
1426
1427 void hlfir::ElementalOp::build(mlir::OpBuilder &builder,
1428 mlir::OperationState &odsState,
1429 mlir::Type resultType, mlir::Value shape,
1430 mlir::Value mold, mlir::ValueRange typeparams,
1431 bool isUnordered) {
1432 odsState.addTypes(resultType);
1433 buildElemental<hlfir::ElementalOp>(builder, odsState, shape, mold, typeparams,
1434 isUnordered);
1435 }
1436
1437 mlir::Value hlfir::ElementalOp::getElementEntity() {
1438 return mlir::cast<hlfir::YieldElementOp>(getBody()->back()).getElementValue();
1439 }
1440
1441 llvm::LogicalResult hlfir::ElementalOp::verify() {
1442 mlir::Value mold = getMold();
1443 hlfir::ExprType resultType = mlir::cast<hlfir::ExprType>(getType());
1444 if (!!mold != resultType.isPolymorphic())
1445 return emitOpError("result must be polymorphic when mold is present "
1446 "and vice versa");
1447
1448 return mlir::success();
1449 }
1450
1451 //===----------------------------------------------------------------------===//
1452 // ApplyOp
1453 //===----------------------------------------------------------------------===//
1454
1455 void hlfir::ApplyOp::build(mlir::OpBuilder &builder,
1456 mlir::OperationState &odsState, mlir::Value expr,
1457 mlir::ValueRange indices,
1458 mlir::ValueRange typeparams) {
1459 mlir::Type resultType = expr.getType();
1460 if (auto exprType = mlir::dyn_cast<hlfir::ExprType>(resultType))
1461 resultType = exprType.getElementExprType();
1462 build(builder, odsState, resultType, expr, indices, typeparams);
1463 }
1464
1465 //===----------------------------------------------------------------------===//
1466 // NullOp
1467 //===----------------------------------------------------------------------===//
1468
1469 void hlfir::NullOp::build(mlir::OpBuilder &builder,
1470 mlir::OperationState &odsState) {
1471 return build(builder, odsState,
1472 fir::ReferenceType::get(builder.getNoneType()));
1473 }
1474
1475 //===----------------------------------------------------------------------===//
1476 // DestroyOp
1477 //===----------------------------------------------------------------------===//
1478
1479 llvm::LogicalResult hlfir::DestroyOp::verify() {
1480 if (mustFinalizeExpr()) {
1481 mlir::Value expr = getExpr();
1482 hlfir::ExprType exprTy = mlir::cast<hlfir::ExprType>(expr.getType());
1483 mlir::Type elemTy = hlfir::getFortranElementType(exprTy);
1484 if (!mlir::isa<fir::RecordType>(elemTy))
1485 return emitOpError(
1486 "the element type must be finalizable, when 'finalize' is set");
1487 }
1488
1489 return mlir::success();
1490 }
1491
1492 //===----------------------------------------------------------------------===//
1493 // CopyInOp
1494 //===----------------------------------------------------------------------===//
1495
1496 void hlfir::CopyInOp::build(mlir::OpBuilder &builder,
1497 mlir::OperationState &odsState, mlir::Value var,
1498 mlir::Value tempBox, mlir::Value var_is_present) {
1499 return build(builder, odsState, {var.getType(), builder.getI1Type()}, var,
1500 tempBox, var_is_present);
1501 }
1502
1503 //===----------------------------------------------------------------------===//
1504 // ShapeOfOp
1505 //===----------------------------------------------------------------------===//
1506
1507 void hlfir::ShapeOfOp::build(mlir::OpBuilder &builder,
1508 mlir::OperationState &result, mlir::Value expr) {
1509 hlfir::ExprType exprTy = mlir::cast<hlfir::ExprType>(expr.getType());
1510 mlir::Type type = fir::ShapeType::get(builder.getContext(), exprTy.getRank());
1511 build(builder, result, type, expr);
1512 }
1513
1514 std::size_t hlfir::ShapeOfOp::getRank() {
1515 mlir::Type resTy = getResult().getType();
1516 fir::ShapeType shape = mlir::cast<fir::ShapeType>(resTy);
1517 return shape.getRank();
1518 }
1519
1520 llvm::LogicalResult hlfir::ShapeOfOp::verify() {
1521 mlir::Value expr = getExpr();
1522 hlfir::ExprType exprTy = mlir::cast<hlfir::ExprType>(expr.getType());
1523 std::size_t exprRank = exprTy.getShape().size();
1524
1525 if (exprRank == 0)
1526 return emitOpError("cannot get the shape of a shape-less expression");
1527
1528 std::size_t shapeRank = getRank();
1529 if (shapeRank != exprRank)
1530 return emitOpError("result rank and expr rank do not match");
1531
1532 return mlir::success();
1533 }
1534
1535 llvm::LogicalResult
1536 hlfir::ShapeOfOp::canonicalize(ShapeOfOp shapeOf,
1537 mlir::PatternRewriter &rewriter) {
1538 // if extent information is available at compile time, immediately fold the
1539 // hlfir.shape_of into a fir.shape
1540 mlir::Location loc = shapeOf.getLoc();
1541 hlfir::ExprType expr =
1542 mlir::cast<hlfir::ExprType>(shapeOf.getExpr().getType());
1543
1544 mlir::Value shape = hlfir::genExprShape(rewriter, loc, expr);
1545 if (!shape)
1546 // shape information is not available at compile time
1547 return llvm::LogicalResult::failure();
1548
1549 rewriter.replaceAllUsesWith(shapeOf.getResult(), shape);
1550 rewriter.eraseOp(shapeOf);
1551 return llvm::LogicalResult::success();
1552 }
1553
1554 //===----------------------------------------------------------------------===//
1555 // GetExtent
1556 //===----------------------------------------------------------------------===//
1557
1558 void hlfir::GetExtentOp::build(mlir::OpBuilder &builder,
1559 mlir::OperationState &result, mlir::Value shape,
1560 unsigned dim) {
1561 mlir::Type indexTy = builder.getIndexType();
1562 mlir::IntegerAttr dimAttr = mlir::IntegerAttr::get(indexTy, dim);
1563 build(builder, result, indexTy, shape, dimAttr);
1564 }
1565
1566 llvm::LogicalResult hlfir::GetExtentOp::verify() {
1567 fir::ShapeType shapeTy = mlir::cast<fir::ShapeType>(getShape().getType());
1568 std::uint64_t rank = shapeTy.getRank();
1569 llvm::APInt dim = getDim();
1570 if (dim.sge(rank))
1571 return emitOpError("dimension index out of bounds");
1572 return mlir::success();
1573 }
1574
1575 //===----------------------------------------------------------------------===//
1576 // RegionAssignOp
1577 //===----------------------------------------------------------------------===//
1578
1579 /// Add a fir.end terminator to a parsed region if it does not already has a
1580 /// terminator.
1581 static void ensureTerminator(mlir::Region &region, mlir::Builder &builder,
1582 mlir::Location loc) {
1583 // Borrow YielOp::ensureTerminator MLIR generated implementation to add a
1584 // fir.end if there is no terminator. This has nothing to do with YielOp,
1585 // other than the fact that yieldOp has the
1586 // SingleBlocklicitTerminator<"fir::FirEndOp"> interface that
1587 // cannot be added on other HLFIR operations with several regions which are
1588 // not all terminated the same way.
1589 hlfir::YieldOp::ensureTerminator(region, builder, loc);
1590 }
1591
1592 mlir::ParseResult hlfir::RegionAssignOp::parse(mlir::OpAsmParser &parser,
1593 mlir::OperationState &result) {
1594 mlir::Region &rhsRegion = *result.addRegion();
1595 if (parser.parseRegion(rhsRegion))
1596 return mlir::failure();
1597 mlir::Region &lhsRegion = *result.addRegion();
1598 if (parser.parseKeyword("to") || parser.parseRegion(lhsRegion))
1599 return mlir::failure();
1600 mlir::Region &userDefinedAssignmentRegion = *result.addRegion();
1601 if (succeeded(parser.parseOptionalKeyword("user_defined_assign"))) {
1602 mlir::OpAsmParser::Argument rhsArg, lhsArg;
1603 if (parser.parseLParen() || parser.parseArgument(rhsArg) ||
1604 parser.parseColon() || parser.parseType(rhsArg.type) ||
1605 parser.parseRParen() || parser.parseKeyword("to") ||
1606 parser.parseLParen() || parser.parseArgument(lhsArg) ||
1607 parser.parseColon() || parser.parseType(lhsArg.type) ||
1608 parser.parseRParen())
1609 return mlir::failure();
1610 if (parser.parseRegion(userDefinedAssignmentRegion, {rhsArg, lhsArg}))
1611 return mlir::failure();
1612 ensureTerminator(userDefinedAssignmentRegion, parser.getBuilder(),
1613 result.location);
1614 }
1615 return mlir::success();
1616 }
1617
1618 void hlfir::RegionAssignOp::print(mlir::OpAsmPrinter &p) {
1619 p << " ";
1620 p.printRegion(getRhsRegion(), /*printEntryBlockArgs=*/false,
1621 /*printBlockTerminators=*/true);
1622 p << " to ";
1623 p.printRegion(getLhsRegion(), /*printEntryBlockArgs=*/false,
1624 /*printBlockTerminators=*/true);
1625 if (!getUserDefinedAssignment().empty()) {
1626 p << " user_defined_assign ";
1627 mlir::Value userAssignmentRhs = getUserAssignmentRhs();
1628 mlir::Value userAssignmentLhs = getUserAssignmentLhs();
1629 p << " (" << userAssignmentRhs << ": " << userAssignmentRhs.getType()
1630 << ") to (";
1631 p << userAssignmentLhs << ": " << userAssignmentLhs.getType() << ") ";
1632 p.printRegion(getUserDefinedAssignment(), /*printEntryBlockArgs=*/false,
1633 /*printBlockTerminators=*/false);
1634 }
1635 }
1636
1637 static mlir::Operation *getTerminator(mlir::Region &region) {
1638 if (region.empty() || region.back().empty())
1639 return nullptr;
1640 return &region.back().back();
1641 }
1642
1643 llvm::LogicalResult hlfir::RegionAssignOp::verify() {
1644 if (!mlir::isa_and_nonnull<hlfir::YieldOp>(getTerminator(getRhsRegion())))
1645 return emitOpError(
1646 "right-hand side region must be terminated by an hlfir.yield");
1647 if (!mlir::isa_and_nonnull<hlfir::YieldOp, hlfir::ElementalAddrOp>(
1648 getTerminator(getLhsRegion())))
1649 return emitOpError("left-hand side region must be terminated by an "
1650 "hlfir.yield or hlfir.elemental_addr");
1651 return mlir::success();
1652 }
1653
1654 //===----------------------------------------------------------------------===//
1655 // YieldOp
1656 //===----------------------------------------------------------------------===//
1657
1658 static mlir::ParseResult parseYieldOpCleanup(mlir::OpAsmParser &parser,
1659 mlir::Region &cleanup) {
1660 if (succeeded(parser.parseOptionalKeyword("cleanup"))) {
1661 if (parser.parseRegion(cleanup, /*arguments=*/{},
1662 /*argTypes=*/{}))
1663 return mlir::failure();
1664 hlfir::YieldOp::ensureTerminator(cleanup, parser.getBuilder(),
1665 parser.getBuilder().getUnknownLoc());
1666 }
1667 return mlir::success();
1668 }
1669
1670 template <typename YieldOp>
1671 static void printYieldOpCleanup(mlir::OpAsmPrinter &p, YieldOp yieldOp,
1672 mlir::Region &cleanup) {
1673 if (!cleanup.empty()) {
1674 p << "cleanup ";
1675 p.printRegion(cleanup, /*printEntryBlockArgs=*/false,
1676 /*printBlockTerminators=*/false);
1677 }
1678 }
1679
1680 //===----------------------------------------------------------------------===//
1681 // ElementalAddrOp
1682 //===----------------------------------------------------------------------===//
1683
1684 void hlfir::ElementalAddrOp::build(mlir::OpBuilder &builder,
1685 mlir::OperationState &odsState,
1686 mlir::Value shape, mlir::Value mold,
1687 mlir::ValueRange typeparams,
1688 bool isUnordered) {
1689 buildElemental<hlfir::ElementalAddrOp>(builder, odsState, shape, mold,
1690 typeparams, isUnordered);
1691 // Push cleanUp region.
1692 odsState.addRegion();
1693 }
1694
1695 llvm::LogicalResult hlfir::ElementalAddrOp::verify() {
1696 hlfir::YieldOp yieldOp =
1697 mlir::dyn_cast_or_null<hlfir::YieldOp>(getTerminator(getBody()));
1698 if (!yieldOp)
1699 return emitOpError("body region must be terminated by an hlfir.yield");
1700 mlir::Type elementAddrType = yieldOp.getEntity().getType();
1701 if (!hlfir::isFortranVariableType(elementAddrType) ||
1702 mlir::isa<fir::SequenceType>(
1703 hlfir::getFortranElementOrSequenceType(elementAddrType)))
1704 return emitOpError("body must compute the address of a scalar entity");
1705 unsigned shapeRank =
1706 mlir::cast<fir::ShapeType>(getShape().getType()).getRank();
1707 if (shapeRank != getIndices().size())
1708 return emitOpError("body number of indices must match shape rank");
1709 return mlir::success();
1710 }
1711
1712 hlfir::YieldOp hlfir::ElementalAddrOp::getYieldOp() {
1713 hlfir::YieldOp yieldOp =
1714 mlir::dyn_cast_or_null<hlfir::YieldOp>(getTerminator(getBody()));
1715 assert(yieldOp && "element_addr is ill-formed");
1716 return yieldOp;
1717 }
1718
1719 mlir::Value hlfir::ElementalAddrOp::getElementEntity() {
1720 return getYieldOp().getEntity();
1721 }
1722
1723 mlir::Region *hlfir::ElementalAddrOp::getElementCleanup() {
1724 mlir::Region *cleanup = &getYieldOp().getCleanup();
1725 return cleanup->empty() ? nullptr : cleanup;
1726 }
1727
1728 //===----------------------------------------------------------------------===//
1729 // OrderedAssignmentTreeOpInterface
1730 //===----------------------------------------------------------------------===//
1731
1732 llvm::LogicalResult hlfir::OrderedAssignmentTreeOpInterface::verifyImpl() {
1733 if (mlir::Region *body = getSubTreeRegion())
1734 if (!body->empty())
1735 for (mlir::Operation &op : body->front())
1736 if (!mlir::isa<hlfir::OrderedAssignmentTreeOpInterface, fir::FirEndOp>(
1737 op))
1738 return emitOpError(
1739 "body region must only contain OrderedAssignmentTreeOpInterface "
1740 "operations or fir.end");
1741 return mlir::success();
1742 }
1743
1744 //===----------------------------------------------------------------------===//
1745 // ForallOp
1746 //===----------------------------------------------------------------------===//
1747
1748 static mlir::ParseResult parseForallOpBody(mlir::OpAsmParser &parser,
1749 mlir::Region &body) {
1750 mlir::OpAsmParser::Argument bodyArg;
1751 if (parser.parseLParen() || parser.parseArgument(bodyArg) ||
1752 parser.parseColon() || parser.parseType(bodyArg.type) ||
1753 parser.parseRParen())
1754 return mlir::failure();
1755 if (parser.parseRegion(body, {bodyArg}))
1756 return mlir::failure();
1757 ensureTerminator(body, parser.getBuilder(),
1758 parser.getBuilder().getUnknownLoc());
1759 return mlir::success();
1760 }
1761
1762 static void printForallOpBody(mlir::OpAsmPrinter &p, hlfir::ForallOp forall,
1763 mlir::Region &body) {
1764 mlir::Value forallIndex = forall.getForallIndexValue();
1765 p << " (" << forallIndex << ": " << forallIndex.getType() << ") ";
1766 p.printRegion(body, /*printEntryBlockArgs=*/false,
1767 /*printBlockTerminators=*/false);
1768 }
1769
1770 /// Predicate implementation of YieldIntegerOrEmpty.
1771 static bool yieldsIntegerOrEmpty(mlir::Region &region) {
1772 if (region.empty())
1773 return true;
1774 auto yield = mlir::dyn_cast_or_null<hlfir::YieldOp>(getTerminator(region));
1775 return yield && fir::isa_integer(yield.getEntity().getType());
1776 }
1777
1778 //===----------------------------------------------------------------------===//
1779 // ForallMaskOp
1780 //===----------------------------------------------------------------------===//
1781
1782 static mlir::ParseResult parseAssignmentMaskOpBody(mlir::OpAsmParser &parser,
1783 mlir::Region &body) {
1784 if (parser.parseRegion(body))
1785 return mlir::failure();
1786 ensureTerminator(body, parser.getBuilder(),
1787 parser.getBuilder().getUnknownLoc());
1788 return mlir::success();
1789 }
1790
1791 template <typename ConcreteOp>
1792 static void printAssignmentMaskOpBody(mlir::OpAsmPrinter &p, ConcreteOp,
1793 mlir::Region &body) {
1794 // ElseWhereOp is a WhereOp/ElseWhereOp terminator that should be printed.
1795 bool printBlockTerminators =
1796 !body.empty() &&
1797 mlir::isa_and_nonnull<hlfir::ElseWhereOp>(body.back().getTerminator());
1798 p.printRegion(body, /*printEntryBlockArgs=*/false, printBlockTerminators);
1799 }
1800
1801 static bool yieldsLogical(mlir::Region &region, bool mustBeScalarI1) {
1802 if (region.empty())
1803 return false;
1804 auto yield = mlir::dyn_cast_or_null<hlfir::YieldOp>(getTerminator(region));
1805 if (!yield)
1806 return false;
1807 mlir::Type yieldType = yield.getEntity().getType();
1808 if (mustBeScalarI1)
1809 return hlfir::isI1Type(yieldType);
1810 return hlfir::isMaskArgument(yieldType) &&
1811 mlir::isa<fir::SequenceType>(
1812 hlfir::getFortranElementOrSequenceType(yieldType));
1813 }
1814
1815 llvm::LogicalResult hlfir::ForallMaskOp::verify() {
1816 if (!yieldsLogical(getMaskRegion(), /*mustBeScalarI1=*/true))
1817 return emitOpError("mask region must yield a scalar i1");
1818 mlir::Operation *op = getOperation();
1819 hlfir::ForallOp forallOp =
1820 mlir::dyn_cast_or_null<hlfir::ForallOp>(op->getParentOp());
1821 if (!forallOp || op->getParentRegion() != &forallOp.getBody())
1822 return emitOpError("must be inside the body region of an hlfir.forall");
1823 return mlir::success();
1824 }
1825
1826 //===----------------------------------------------------------------------===//
1827 // WhereOp and ElseWhereOp
1828 //===----------------------------------------------------------------------===//
1829
1830 template <typename ConcreteOp>
1831 static llvm::LogicalResult verifyWhereAndElseWhereBody(ConcreteOp &concreteOp) {
1832 for (mlir::Operation &op : concreteOp.getBody().front())
1833 if (mlir::isa<hlfir::ForallOp>(op))
1834 return concreteOp.emitOpError(
1835 "body region must not contain hlfir.forall");
1836 return mlir::success();
1837 }
1838
1839 llvm::LogicalResult hlfir::WhereOp::verify() {
1840 if (!yieldsLogical(getMaskRegion(), /*mustBeScalarI1=*/false))
1841 return emitOpError("mask region must yield a logical array");
1842 return verifyWhereAndElseWhereBody(*this);
1843 }
1844
1845 llvm::LogicalResult hlfir::ElseWhereOp::verify() {
1846 if (!getMaskRegion().empty())
1847 if (!yieldsLogical(getMaskRegion(), /*mustBeScalarI1=*/false))
1848 return emitOpError(
1849 "mask region must yield a logical array when provided");
1850 return verifyWhereAndElseWhereBody(*this);
1851 }
1852
1853 //===----------------------------------------------------------------------===//
1854 // ForallIndexOp
1855 //===----------------------------------------------------------------------===//
1856
1857 llvm::LogicalResult
1858 hlfir::ForallIndexOp::canonicalize(hlfir::ForallIndexOp indexOp,
1859 mlir::PatternRewriter &rewriter) {
1860 for (mlir::Operation *user : indexOp->getResult(0).getUsers())
1861 if (!mlir::isa<fir::LoadOp>(user))
1862 return mlir::failure();
1863
1864 auto insertPt = rewriter.saveInsertionPoint();
1865 llvm::SmallVector<mlir::Operation *> users(indexOp->getResult(0).getUsers());
1866 for (mlir::Operation *user : users)
1867 if (auto loadOp = mlir::dyn_cast<fir::LoadOp>(user)) {
1868 rewriter.setInsertionPoint(loadOp);
1869 rewriter.replaceOpWithNewOp<fir::ConvertOp>(
1870 user, loadOp.getResult().getType(), indexOp.getIndex());
1871 }
1872 rewriter.restoreInsertionPoint(insertPt);
1873 rewriter.eraseOp(indexOp);
1874 return mlir::success();
1875 }
1876
1877 //===----------------------------------------------------------------------===//
1878 // CharExtremumOp
1879 //===----------------------------------------------------------------------===//
1880
1881 llvm::LogicalResult hlfir::CharExtremumOp::verify() {
1882 if (getStrings().size() < 2)
1883 return emitOpError("must be provided at least two string operands");
1884 unsigned kind = getCharacterKind(getResult().getType());
1885 for (auto string : getStrings())
1886 if (kind != getCharacterKind(string.getType()))
1887 return emitOpError("strings must have the same KIND as the result type");
1888 return mlir::success();
1889 }
1890
1891 void hlfir::CharExtremumOp::build(mlir::OpBuilder &builder,
1892 mlir::OperationState &result,
1893 hlfir::CharExtremumPredicate predicate,
1894 mlir::ValueRange strings) {
1895
1896 fir::CharacterType::LenType resultTypeLen = 0;
1897 assert(!strings.empty() && "must contain operands");
1898 unsigned kind = getCharacterKind(strings[0].getType());
1899 for (auto string : strings)
1900 if (auto cstLen = getCharacterLengthIfStatic(string.getType())) {
1901 resultTypeLen = std::max(resultTypeLen, *cstLen);
1902 } else {
1903 resultTypeLen = fir::CharacterType::unknownLen();
1904 break;
1905 }
1906 auto resultType = hlfir::ExprType::get(
1907 builder.getContext(), hlfir::ExprType::Shape{},
1908 fir::CharacterType::get(builder.getContext(), kind, resultTypeLen),
1909 false);
1910
1911 build(builder, result, resultType, predicate, strings);
1912 }
1913
1914 void hlfir::CharExtremumOp::getEffects(
1915 llvm::SmallVectorImpl<
1916 mlir::SideEffects::EffectInstance<mlir::MemoryEffects::Effect>>
1917 &effects) {
1918 getIntrinsicEffects(getOperation(), effects);
1919 }
1920
1921 //===----------------------------------------------------------------------===//
1922 // GetLength
1923 //===----------------------------------------------------------------------===//
1924
1925 llvm::LogicalResult
1926 hlfir::GetLengthOp::canonicalize(GetLengthOp getLength,
1927 mlir::PatternRewriter &rewriter) {
1928 mlir::Location loc = getLength.getLoc();
1929 auto exprTy = mlir::cast<hlfir::ExprType>(getLength.getExpr().getType());
1930 auto charTy = mlir::cast<fir::CharacterType>(exprTy.getElementType());
1931 if (!charTy.hasConstantLen())
1932 return mlir::failure();
1933
1934 mlir::Type indexTy = rewriter.getIndexType();
1935 auto cstLen = rewriter.create<mlir::arith::ConstantOp>(
1936 loc, indexTy, mlir::IntegerAttr::get(indexTy, charTy.getLen()));
1937 rewriter.replaceOp(getLength, cstLen);
1938 return mlir::success();
1939 }
1940
1941 #include "flang/Optimizer/HLFIR/HLFIROpInterfaces.cpp.inc"
1942 #define GET_OP_CLASSES
1943 #include "flang/Optimizer/HLFIR/HLFIREnums.cpp.inc"
1944 #include "flang/Optimizer/HLFIR/HLFIROps.cpp.inc"