[TargetVersion] Only enable on RISC-V and AArch64 (#115991)
[llvm-project.git] / flang / lib / Lower / ConvertExprToHLFIR.cpp
blobe93fbc562f9b13f0f21f6e079e456eefd16f6516
1 //===-- ConvertExprToHLFIR.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/
11 //===----------------------------------------------------------------------===//
13 #include "flang/Lower/ConvertExprToHLFIR.h"
14 #include "flang/Evaluate/shape.h"
15 #include "flang/Lower/AbstractConverter.h"
16 #include "flang/Lower/Allocatable.h"
17 #include "flang/Lower/CallInterface.h"
18 #include "flang/Lower/ConvertArrayConstructor.h"
19 #include "flang/Lower/ConvertCall.h"
20 #include "flang/Lower/ConvertConstant.h"
21 #include "flang/Lower/ConvertProcedureDesignator.h"
22 #include "flang/Lower/ConvertType.h"
23 #include "flang/Lower/ConvertVariable.h"
24 #include "flang/Lower/StatementContext.h"
25 #include "flang/Lower/SymbolMap.h"
26 #include "flang/Optimizer/Builder/Complex.h"
27 #include "flang/Optimizer/Builder/IntrinsicCall.h"
28 #include "flang/Optimizer/Builder/MutableBox.h"
29 #include "flang/Optimizer/Builder/Runtime/Character.h"
30 #include "flang/Optimizer/Builder/Runtime/Derived.h"
31 #include "flang/Optimizer/Builder/Runtime/Pointer.h"
32 #include "flang/Optimizer/Builder/Todo.h"
33 #include "flang/Optimizer/HLFIR/HLFIROps.h"
34 #include "llvm/ADT/TypeSwitch.h"
35 #include <optional>
37 namespace {
39 /// Lower Designators to HLFIR.
40 class HlfirDesignatorBuilder {
41 private:
42 /// Internal entry point on the rightest part of a evaluate::Designator.
43 template <typename T>
44 hlfir::EntityWithAttributes
45 genLeafPartRef(const T &designatorNode,
46 bool vectorSubscriptDesignatorToValue) {
47 hlfir::EntityWithAttributes result = gen(designatorNode);
48 if (vectorSubscriptDesignatorToValue)
49 return turnVectorSubscriptedDesignatorIntoValue(result);
50 return result;
53 hlfir::EntityWithAttributes
54 genDesignatorExpr(const Fortran::lower::SomeExpr &designatorExpr,
55 bool vectorSubscriptDesignatorToValue = true);
57 public:
58 HlfirDesignatorBuilder(mlir::Location loc,
59 Fortran::lower::AbstractConverter &converter,
60 Fortran::lower::SymMap &symMap,
61 Fortran::lower::StatementContext &stmtCtx)
62 : converter{converter}, symMap{symMap}, stmtCtx{stmtCtx}, loc{loc} {}
64 /// Public entry points to lower a Designator<T> (given its .u member, to
65 /// avoid the template arguments which does not matter here).
66 /// This lowers a designator to an hlfir variable SSA value (that can be
67 /// assigned to), except for vector subscripted designators that are
68 /// lowered by default to hlfir.expr value since they cannot be
69 /// represented as HLFIR variable SSA values.
71 // Character designators variant contains substrings
72 using CharacterDesignators =
73 decltype(Fortran::evaluate::Designator<Fortran::evaluate::Type<
74 Fortran::evaluate::TypeCategory::Character, 1>>::u);
75 hlfir::EntityWithAttributes
76 gen(const CharacterDesignators &designatorVariant,
77 bool vectorSubscriptDesignatorToValue = true) {
78 return Fortran::common::visit(
79 [&](const auto &x) -> hlfir::EntityWithAttributes {
80 return genLeafPartRef(x, vectorSubscriptDesignatorToValue);
82 designatorVariant);
84 // Character designators variant contains complex parts
85 using RealDesignators =
86 decltype(Fortran::evaluate::Designator<Fortran::evaluate::Type<
87 Fortran::evaluate::TypeCategory::Real, 4>>::u);
88 hlfir::EntityWithAttributes
89 gen(const RealDesignators &designatorVariant,
90 bool vectorSubscriptDesignatorToValue = true) {
91 return Fortran::common::visit(
92 [&](const auto &x) -> hlfir::EntityWithAttributes {
93 return genLeafPartRef(x, vectorSubscriptDesignatorToValue);
95 designatorVariant);
97 // All other designators are similar
98 using OtherDesignators =
99 decltype(Fortran::evaluate::Designator<Fortran::evaluate::Type<
100 Fortran::evaluate::TypeCategory::Integer, 4>>::u);
101 hlfir::EntityWithAttributes
102 gen(const OtherDesignators &designatorVariant,
103 bool vectorSubscriptDesignatorToValue = true) {
104 return Fortran::common::visit(
105 [&](const auto &x) -> hlfir::EntityWithAttributes {
106 return genLeafPartRef(x, vectorSubscriptDesignatorToValue);
108 designatorVariant);
111 hlfir::EntityWithAttributes
112 genNamedEntity(const Fortran::evaluate::NamedEntity &namedEntity,
113 bool vectorSubscriptDesignatorToValue = true) {
114 if (namedEntity.IsSymbol())
115 return genLeafPartRef(
116 Fortran::evaluate::SymbolRef{namedEntity.GetLastSymbol()},
117 vectorSubscriptDesignatorToValue);
118 return genLeafPartRef(namedEntity.GetComponent(),
119 vectorSubscriptDesignatorToValue);
122 /// Public entry point to lower a vector subscripted designator to
123 /// an hlfir::ElementalAddrOp.
124 hlfir::ElementalAddrOp convertVectorSubscriptedExprToElementalAddr(
125 const Fortran::lower::SomeExpr &designatorExpr);
127 mlir::Value genComponentShape(const Fortran::semantics::Symbol &componentSym,
128 mlir::Type fieldType) {
129 // For pointers and allocatable components, the
130 // shape is deferred and should not be loaded now to preserve
131 // pointer/allocatable aspects.
132 if (componentSym.Rank() == 0 ||
133 Fortran::semantics::IsAllocatableOrObjectPointer(&componentSym) ||
134 Fortran::semantics::IsProcedurePointer(&componentSym))
135 return mlir::Value{};
137 fir::FirOpBuilder &builder = getBuilder();
138 mlir::Location loc = getLoc();
139 mlir::Type idxTy = builder.getIndexType();
140 llvm::SmallVector<mlir::Value> extents;
141 auto seqTy = mlir::cast<fir::SequenceType>(
142 hlfir::getFortranElementOrSequenceType(fieldType));
143 for (auto extent : seqTy.getShape()) {
144 if (extent == fir::SequenceType::getUnknownExtent()) {
145 // We have already generated invalid hlfir.declare
146 // without the type parameters and probably invalid storage
147 // for the variable (e.g. fir.alloca without type parameters).
148 // So this TODO here is a little bit late, but it matches
149 // the non-HLFIR path.
150 TODO(loc, "array component shape depending on length parameters");
152 extents.push_back(builder.createIntegerConstant(loc, idxTy, extent));
154 if (!mayHaveNonDefaultLowerBounds(componentSym))
155 return builder.create<fir::ShapeOp>(loc, extents);
157 llvm::SmallVector<mlir::Value> lbounds;
158 if (const auto *objDetails =
159 componentSym.detailsIf<Fortran::semantics::ObjectEntityDetails>())
160 for (const Fortran::semantics::ShapeSpec &bounds : objDetails->shape())
161 if (auto lb = bounds.lbound().GetExplicit())
162 if (auto constant = Fortran::evaluate::ToInt64(*lb))
163 lbounds.push_back(
164 builder.createIntegerConstant(loc, idxTy, *constant));
165 assert(extents.size() == lbounds.size() &&
166 "extents and lower bounds must match");
167 return builder.genShape(loc, lbounds, extents);
170 fir::FortranVariableOpInterface
171 gen(const Fortran::evaluate::DataRef &dataRef) {
172 return Fortran::common::visit(
173 Fortran::common::visitors{[&](const auto &x) { return gen(x); }},
174 dataRef.u);
177 private:
178 /// Struct that is filled while visiting a part-ref (in the "visit" member
179 /// function) before the top level "gen" generates an hlfir.declare for the
180 /// part ref. It contains the lowered pieces of the part-ref that will
181 /// become the operands of an hlfir.declare.
182 struct PartInfo {
183 std::optional<hlfir::Entity> base;
184 std::string componentName{};
185 mlir::Value componentShape;
186 hlfir::DesignateOp::Subscripts subscripts;
187 std::optional<bool> complexPart;
188 mlir::Value resultShape;
189 llvm::SmallVector<mlir::Value> typeParams;
190 llvm::SmallVector<mlir::Value, 2> substring;
193 // Given the value type of a designator (T or fir.array<T>) and the front-end
194 // node for the designator, compute the memory type (fir.class, fir.ref, or
195 // fir.box)...
196 template <typename T>
197 mlir::Type computeDesignatorType(mlir::Type resultValueType,
198 PartInfo &partInfo,
199 const T &designatorNode) {
200 // Get base's shape if its a sequence type with no previously computed
201 // result shape
202 if (partInfo.base && mlir::isa<fir::SequenceType>(resultValueType) &&
203 !partInfo.resultShape)
204 partInfo.resultShape =
205 hlfir::genShape(getLoc(), getBuilder(), *partInfo.base);
206 // Dynamic type of polymorphic base must be kept if the designator is
207 // polymorphic.
208 if (isPolymorphic(designatorNode))
209 return fir::ClassType::get(resultValueType);
210 // Character scalar with dynamic length needs a fir.boxchar to hold the
211 // designator length.
212 auto charType = mlir::dyn_cast<fir::CharacterType>(resultValueType);
213 if (charType && charType.hasDynamicLen())
214 return fir::BoxCharType::get(charType.getContext(), charType.getFKind());
215 // Arrays with non default lower bounds or dynamic length or dynamic extent
216 // need a fir.box to hold the dynamic or lower bound information.
217 if (fir::hasDynamicSize(resultValueType) ||
218 mayHaveNonDefaultLowerBounds(partInfo))
219 return fir::BoxType::get(resultValueType);
220 // Non simply contiguous ref require a fir.box to carry the byte stride.
221 if (mlir::isa<fir::SequenceType>(resultValueType) &&
222 !Fortran::evaluate::IsSimplyContiguous(
223 designatorNode, getConverter().getFoldingContext()))
224 return fir::BoxType::get(resultValueType);
225 // Other designators can be handled as raw addresses.
226 return fir::ReferenceType::get(resultValueType);
229 template <typename T>
230 static bool isPolymorphic(const T &designatorNode) {
231 if constexpr (!std::is_same_v<T, Fortran::evaluate::Substring>) {
232 return Fortran::semantics::IsPolymorphic(designatorNode.GetLastSymbol());
234 return false;
237 template <typename T>
238 /// Generate an hlfir.designate for a part-ref given a filled PartInfo and the
239 /// FIR type for this part-ref.
240 fir::FortranVariableOpInterface genDesignate(mlir::Type resultValueType,
241 PartInfo &partInfo,
242 const T &designatorNode) {
243 mlir::Type designatorType =
244 computeDesignatorType(resultValueType, partInfo, designatorNode);
245 return genDesignate(designatorType, partInfo, /*attributes=*/{});
247 fir::FortranVariableOpInterface
248 genDesignate(mlir::Type designatorType, PartInfo &partInfo,
249 fir::FortranVariableFlagsAttr attributes) {
250 fir::FirOpBuilder &builder = getBuilder();
251 // Once a part with vector subscripts has been lowered, the following
252 // hlfir.designator (for the parts on the right of the designator) must
253 // be lowered inside the hlfir.elemental_addr because they depend on the
254 // hlfir.elemental_addr indices.
255 // All the subsequent Fortran indices however, should be lowered before
256 // the hlfir.elemental_addr because they should only be evaluated once,
257 // hence, the insertion point is restored outside of the
258 // hlfir.elemental_addr after generating the hlfir.designate. Example: in
259 // "X(VECTOR)%COMP(FOO(), BAR())", the calls to bar() and foo() must be
260 // generated outside of the hlfir.elemental, but the related hlfir.designate
261 // that depends on the scalar hlfir.designate of X(VECTOR) that was
262 // generated inside the hlfir.elemental_addr should be generated in the
263 // hlfir.elemental_addr.
264 if (auto elementalAddrOp = getVectorSubscriptElementAddrOp())
265 builder.setInsertionPointToEnd(&elementalAddrOp->getBody().front());
266 auto designate = builder.create<hlfir::DesignateOp>(
267 getLoc(), designatorType, partInfo.base.value().getBase(),
268 partInfo.componentName, partInfo.componentShape, partInfo.subscripts,
269 partInfo.substring, partInfo.complexPart, partInfo.resultShape,
270 partInfo.typeParams, attributes);
271 if (auto elementalAddrOp = getVectorSubscriptElementAddrOp())
272 builder.setInsertionPoint(*elementalAddrOp);
273 return mlir::cast<fir::FortranVariableOpInterface>(
274 designate.getOperation());
277 fir::FortranVariableOpInterface
278 gen(const Fortran::evaluate::SymbolRef &symbolRef) {
279 if (std::optional<fir::FortranVariableOpInterface> varDef =
280 getSymMap().lookupVariableDefinition(symbolRef)) {
281 if (symbolRef->test(Fortran::semantics::Symbol::Flag::CrayPointee)) {
282 // The pointee is represented with a descriptor inheriting
283 // the shape and type parameters of the pointee.
284 // We have to update the base_addr to point to the current
285 // value of the Cray pointer variable.
286 fir::FirOpBuilder &builder = getBuilder();
287 fir::FortranVariableOpInterface ptrVar =
288 gen(Fortran::semantics::GetCrayPointer(symbolRef));
289 mlir::Value ptrAddr = ptrVar.getBase();
291 // Reinterpret the reference to a Cray pointer so that
292 // we have a pointer-compatible value after loading
293 // the Cray pointer value.
294 mlir::Type refPtrType = builder.getRefType(
295 fir::PointerType::get(fir::dyn_cast_ptrEleTy(ptrAddr.getType())));
296 mlir::Value cast = builder.createConvert(loc, refPtrType, ptrAddr);
297 mlir::Value ptrVal = builder.create<fir::LoadOp>(loc, cast);
299 // Update the base_addr to the value of the Cray pointer.
300 // This is a hacky way to do the update, and it may harm
301 // performance around Cray pointer references.
302 // TODO: we should introduce an operation that updates
303 // just the base_addr of the given box. The CodeGen
304 // will just convert it into a single store.
305 fir::runtime::genPointerAssociateScalar(builder, loc, varDef->getBase(),
306 ptrVal);
308 return *varDef;
310 llvm::errs() << *symbolRef << "\n";
311 TODO(getLoc(), "lowering symbol to HLFIR");
314 fir::FortranVariableOpInterface
315 gen(const Fortran::semantics::Symbol &symbol) {
316 Fortran::evaluate::SymbolRef symref{symbol};
317 return gen(symref);
320 fir::FortranVariableOpInterface
321 gen(const Fortran::evaluate::Component &component) {
322 if (Fortran::semantics::IsAllocatableOrPointer(component.GetLastSymbol()))
323 return genWholeAllocatableOrPointerComponent(component);
324 PartInfo partInfo;
325 mlir::Type resultType = visit(component, partInfo);
326 return genDesignate(resultType, partInfo, component);
329 fir::FortranVariableOpInterface
330 gen(const Fortran::evaluate::ArrayRef &arrayRef) {
331 PartInfo partInfo;
332 mlir::Type resultType = visit(arrayRef, partInfo);
333 return genDesignate(resultType, partInfo, arrayRef);
336 fir::FortranVariableOpInterface
337 gen(const Fortran::evaluate::CoarrayRef &coarrayRef) {
338 TODO(getLoc(), "coarray: lowering a reference to a coarray object");
341 mlir::Type visit(const Fortran::evaluate::CoarrayRef &, PartInfo &) {
342 TODO(getLoc(), "coarray: lowering a reference to a coarray object");
345 fir::FortranVariableOpInterface
346 gen(const Fortran::evaluate::ComplexPart &complexPart) {
347 PartInfo partInfo;
348 fir::factory::Complex cmplxHelper(getBuilder(), getLoc());
350 bool complexBit =
351 complexPart.part() == Fortran::evaluate::ComplexPart::Part::IM;
352 partInfo.complexPart = {complexBit};
354 mlir::Type resultType = visit(complexPart.complex(), partInfo);
356 // Determine complex part type
357 mlir::Type base = hlfir::getFortranElementType(resultType);
358 mlir::Type cmplxValueType = cmplxHelper.getComplexPartType(base);
359 mlir::Type designatorType = changeElementType(resultType, cmplxValueType);
361 return genDesignate(designatorType, partInfo, complexPart);
364 fir::FortranVariableOpInterface
365 gen(const Fortran::evaluate::Substring &substring) {
366 PartInfo partInfo;
367 mlir::Type baseStringType = Fortran::common::visit(
368 [&](const auto &x) { return visit(x, partInfo); }, substring.parent());
369 assert(partInfo.typeParams.size() == 1 && "expect base string length");
370 // Compute the substring lower and upper bound.
371 partInfo.substring.push_back(genSubscript(substring.lower()));
372 if (Fortran::evaluate::MaybeExtentExpr upperBound = substring.upper())
373 partInfo.substring.push_back(genSubscript(*upperBound));
374 else
375 partInfo.substring.push_back(partInfo.typeParams[0]);
376 fir::FirOpBuilder &builder = getBuilder();
377 mlir::Location loc = getLoc();
378 mlir::Type idxTy = builder.getIndexType();
379 partInfo.substring[0] =
380 builder.createConvert(loc, idxTy, partInfo.substring[0]);
381 partInfo.substring[1] =
382 builder.createConvert(loc, idxTy, partInfo.substring[1]);
383 // Try using constant length if available. mlir::arith folding would
384 // most likely be able to fold "max(ub-lb+1,0)" too, but getting
385 // the constant length in the FIR types would be harder.
386 std::optional<int64_t> cstLen =
387 Fortran::evaluate::ToInt64(Fortran::evaluate::Fold(
388 getConverter().getFoldingContext(), substring.LEN()));
389 if (cstLen) {
390 partInfo.typeParams[0] =
391 builder.createIntegerConstant(loc, idxTy, *cstLen);
392 } else {
393 // Compute "len = max(ub-lb+1,0)" (Fortran 2018 9.4.1).
394 mlir::Value one = builder.createIntegerConstant(loc, idxTy, 1);
395 auto boundsDiff = builder.create<mlir::arith::SubIOp>(
396 loc, partInfo.substring[1], partInfo.substring[0]);
397 auto rawLen = builder.create<mlir::arith::AddIOp>(loc, boundsDiff, one);
398 partInfo.typeParams[0] =
399 fir::factory::genMaxWithZero(builder, loc, rawLen);
401 auto kind = mlir::cast<fir::CharacterType>(
402 hlfir::getFortranElementType(baseStringType))
403 .getFKind();
404 auto newCharTy = fir::CharacterType::get(
405 baseStringType.getContext(), kind,
406 cstLen ? *cstLen : fir::CharacterType::unknownLen());
407 mlir::Type resultType = changeElementType(baseStringType, newCharTy);
408 return genDesignate(resultType, partInfo, substring);
411 static mlir::Type changeElementType(mlir::Type type, mlir::Type newEleTy) {
412 return llvm::TypeSwitch<mlir::Type, mlir::Type>(type)
413 .Case<fir::SequenceType>([&](fir::SequenceType seqTy) -> mlir::Type {
414 return fir::SequenceType::get(seqTy.getShape(), newEleTy);
416 .Case<fir::PointerType, fir::HeapType, fir::ReferenceType, fir::BoxType,
417 fir::ClassType>([&](auto t) -> mlir::Type {
418 using FIRT = decltype(t);
419 return FIRT::get(changeElementType(t.getEleTy(), newEleTy));
421 .Default([newEleTy](mlir::Type t) -> mlir::Type { return newEleTy; });
424 fir::FortranVariableOpInterface genWholeAllocatableOrPointerComponent(
425 const Fortran::evaluate::Component &component) {
426 // Generate whole allocatable or pointer component reference. The
427 // hlfir.designate result will be a pointer/allocatable.
428 PartInfo partInfo;
429 mlir::Type componentType = visitComponentImpl(component, partInfo).second;
430 mlir::Type designatorType = fir::ReferenceType::get(componentType);
431 fir::FortranVariableFlagsAttr attributes =
432 Fortran::lower::translateSymbolAttributes(getBuilder().getContext(),
433 component.GetLastSymbol());
434 return genDesignate(designatorType, partInfo, attributes);
437 mlir::Type visit(const Fortran::evaluate::DataRef &dataRef,
438 PartInfo &partInfo) {
439 return Fortran::common::visit(
440 [&](const auto &x) { return visit(x, partInfo); }, dataRef.u);
443 mlir::Type
444 visit(const Fortran::evaluate::StaticDataObject::Pointer &staticObject,
445 PartInfo &partInfo) {
446 fir::FirOpBuilder &builder = getBuilder();
447 mlir::Location loc = getLoc();
448 std::optional<std::string> string = staticObject->AsString();
449 // TODO: see if StaticDataObject can be replaced by something based on
450 // Constant<T> to avoid dealing with endianness here for KIND>1.
451 // This will also avoid making string copies here.
452 if (!string)
453 TODO(loc, "StaticDataObject::Pointer substring with kind > 1");
454 fir::ExtendedValue exv =
455 fir::factory::createStringLiteral(builder, getLoc(), *string);
456 auto flags = fir::FortranVariableFlagsAttr::get(
457 builder.getContext(), fir::FortranVariableFlagsEnum::parameter);
458 partInfo.base = hlfir::genDeclare(loc, builder, exv, ".stringlit", flags);
459 partInfo.typeParams.push_back(fir::getLen(exv));
460 return partInfo.base->getElementOrSequenceType();
463 mlir::Type visit(const Fortran::evaluate::SymbolRef &symbolRef,
464 PartInfo &partInfo) {
465 // A symbol is only visited if there is a following array, substring, or
466 // complex reference. If the entity is a pointer or allocatable, this
467 // reference designates the target, so the pointer, allocatable must be
468 // dereferenced here.
469 partInfo.base =
470 hlfir::derefPointersAndAllocatables(loc, getBuilder(), gen(symbolRef));
471 hlfir::genLengthParameters(loc, getBuilder(), *partInfo.base,
472 partInfo.typeParams);
473 return partInfo.base->getElementOrSequenceType();
476 mlir::Type visit(const Fortran::evaluate::ArrayRef &arrayRef,
477 PartInfo &partInfo) {
478 mlir::Type baseType;
479 if (const auto *component = arrayRef.base().UnwrapComponent()) {
480 // Pointers and allocatable components must be dereferenced since the
481 // array ref designates the target (this is done in "visit"). Other
482 // components need special care to deal with the array%array_comp(indices)
483 // case.
484 if (Fortran::semantics::IsAllocatableOrObjectPointer(
485 &component->GetLastSymbol()))
486 baseType = visit(*component, partInfo);
487 else
488 baseType = hlfir::getFortranElementOrSequenceType(
489 visitComponentImpl(*component, partInfo).second);
490 } else {
491 baseType = visit(arrayRef.base().GetLastSymbol(), partInfo);
494 fir::FirOpBuilder &builder = getBuilder();
495 mlir::Location loc = getLoc();
496 mlir::Type idxTy = builder.getIndexType();
497 llvm::SmallVector<std::pair<mlir::Value, mlir::Value>> bounds;
498 auto getBaseBounds = [&](unsigned i) {
499 if (bounds.empty()) {
500 if (partInfo.componentName.empty()) {
501 bounds = hlfir::genBounds(loc, builder, partInfo.base.value());
502 } else {
503 assert(
504 partInfo.componentShape &&
505 "implicit array section bounds must come from component shape");
506 bounds = hlfir::genBounds(loc, builder, partInfo.componentShape);
508 assert(!bounds.empty() &&
509 "failed to compute implicit array section bounds");
511 return bounds[i];
513 auto frontEndResultShape =
514 Fortran::evaluate::GetShape(converter.getFoldingContext(), arrayRef);
515 auto tryGettingExtentFromFrontEnd =
516 [&](unsigned dim) -> std::pair<mlir::Value, fir::SequenceType::Extent> {
517 // Use constant extent if possible. The main advantage to do this now
518 // is to get the best FIR array types as possible while lowering.
519 if (frontEndResultShape)
520 if (auto maybeI64 =
521 Fortran::evaluate::ToInt64(frontEndResultShape->at(dim)))
522 return {builder.createIntegerConstant(loc, idxTy, *maybeI64),
523 *maybeI64};
524 return {mlir::Value{}, fir::SequenceType::getUnknownExtent()};
526 llvm::SmallVector<mlir::Value> resultExtents;
527 fir::SequenceType::Shape resultTypeShape;
528 bool sawVectorSubscripts = false;
529 for (auto subscript : llvm::enumerate(arrayRef.subscript())) {
530 if (const auto *triplet =
531 std::get_if<Fortran::evaluate::Triplet>(&subscript.value().u)) {
532 mlir::Value lb, ub;
533 if (const auto &lbExpr = triplet->lower())
534 lb = genSubscript(*lbExpr);
535 else
536 lb = getBaseBounds(subscript.index()).first;
537 if (const auto &ubExpr = triplet->upper())
538 ub = genSubscript(*ubExpr);
539 else
540 ub = getBaseBounds(subscript.index()).second;
541 lb = builder.createConvert(loc, idxTy, lb);
542 ub = builder.createConvert(loc, idxTy, ub);
543 mlir::Value stride = genSubscript(triplet->stride());
544 stride = builder.createConvert(loc, idxTy, stride);
545 auto [extentValue, shapeExtent] =
546 tryGettingExtentFromFrontEnd(resultExtents.size());
547 resultTypeShape.push_back(shapeExtent);
548 if (!extentValue)
549 extentValue =
550 builder.genExtentFromTriplet(loc, lb, ub, stride, idxTy);
551 resultExtents.push_back(extentValue);
552 partInfo.subscripts.emplace_back(
553 hlfir::DesignateOp::Triplet{lb, ub, stride});
554 } else {
555 const auto &expr =
556 std::get<Fortran::evaluate::IndirectSubscriptIntegerExpr>(
557 subscript.value().u)
558 .value();
559 hlfir::Entity subscript = genSubscript(expr);
560 partInfo.subscripts.push_back(subscript);
561 if (expr.Rank() > 0) {
562 sawVectorSubscripts = true;
563 auto [extentValue, shapeExtent] =
564 tryGettingExtentFromFrontEnd(resultExtents.size());
565 resultTypeShape.push_back(shapeExtent);
566 if (!extentValue)
567 extentValue = hlfir::genExtent(loc, builder, subscript, /*dim=*/0);
568 resultExtents.push_back(extentValue);
572 assert(resultExtents.size() == resultTypeShape.size() &&
573 "inconsistent hlfir.designate shape");
575 // For vector subscripts, create an hlfir.elemental_addr and continue
576 // lowering the designator inside it as if it was addressing an element of
577 // the vector subscripts.
578 if (sawVectorSubscripts)
579 return createVectorSubscriptElementAddrOp(partInfo, baseType,
580 resultExtents);
582 mlir::Type resultType =
583 mlir::cast<fir::SequenceType>(baseType).getElementType();
584 if (!resultTypeShape.empty()) {
585 // Ranked array section. The result shape comes from the array section
586 // subscripts.
587 resultType = fir::SequenceType::get(resultTypeShape, resultType);
588 assert(!partInfo.resultShape &&
589 "Fortran designator can only have one ranked part");
590 partInfo.resultShape = builder.genShape(loc, resultExtents);
591 } else if (!partInfo.componentName.empty() &&
592 partInfo.base.value().isArray()) {
593 // This is an array%array_comp(indices) reference. Keep the
594 // shape of the base array and not the array_comp.
595 auto compBaseTy = partInfo.base->getElementOrSequenceType();
596 resultType = changeElementType(compBaseTy, resultType);
597 assert(!partInfo.resultShape && "should not have been computed already");
598 partInfo.resultShape = hlfir::genShape(loc, builder, *partInfo.base);
600 return resultType;
603 static bool
604 mayHaveNonDefaultLowerBounds(const Fortran::semantics::Symbol &componentSym) {
605 if (const auto *objDetails =
606 componentSym.detailsIf<Fortran::semantics::ObjectEntityDetails>())
607 for (const Fortran::semantics::ShapeSpec &bounds : objDetails->shape())
608 if (auto lb = bounds.lbound().GetExplicit())
609 if (auto constant = Fortran::evaluate::ToInt64(*lb))
610 if (!constant || *constant != 1)
611 return true;
612 return false;
614 static bool mayHaveNonDefaultLowerBounds(const PartInfo &partInfo) {
615 return partInfo.resultShape &&
616 mlir::isa<fir::ShiftType, fir::ShapeShiftType>(
617 partInfo.resultShape.getType());
620 mlir::Type visit(const Fortran::evaluate::Component &component,
621 PartInfo &partInfo) {
622 if (Fortran::semantics::IsAllocatableOrPointer(component.GetLastSymbol())) {
623 // In a visit, the following reference will address the target. Insert
624 // the dereference here.
625 partInfo.base = genWholeAllocatableOrPointerComponent(component);
626 partInfo.base = hlfir::derefPointersAndAllocatables(loc, getBuilder(),
627 *partInfo.base);
628 hlfir::genLengthParameters(loc, getBuilder(), *partInfo.base,
629 partInfo.typeParams);
630 return partInfo.base->getElementOrSequenceType();
632 // This function must be called from contexts where the component is not the
633 // base of an ArrayRef. In these cases, the component cannot be an array
634 // if the base is an array. The code below determines the shape of the
635 // component reference if any.
636 auto [baseType, componentType] = visitComponentImpl(component, partInfo);
637 mlir::Type componentBaseType =
638 hlfir::getFortranElementOrSequenceType(componentType);
639 if (partInfo.base.value().isArray()) {
640 // For array%scalar_comp, the result shape is
641 // the one of the base. Compute it here. Note that the lower bounds of the
642 // base are not the ones of the resulting reference (that are default
643 // ones).
644 partInfo.resultShape = hlfir::genShape(loc, getBuilder(), *partInfo.base);
645 assert(!partInfo.componentShape &&
646 "Fortran designators can only have one ranked part");
647 return changeElementType(baseType, componentBaseType);
650 if (partInfo.complexPart && partInfo.componentShape) {
651 // Treat ...array_comp%im/re as ...array_comp(:,:,...)%im/re
652 // so that the codegen has the full slice triples for the component
653 // readily available.
654 fir::FirOpBuilder &builder = getBuilder();
655 mlir::Type idxTy = builder.getIndexType();
656 mlir::Value one = builder.createIntegerConstant(loc, idxTy, 1);
658 llvm::SmallVector<mlir::Value> resultExtents;
659 // Collect <lb, ub> pairs from the component shape.
660 auto bounds = hlfir::genBounds(loc, builder, partInfo.componentShape);
661 for (auto &boundPair : bounds) {
662 // The default subscripts are <lb, ub, 1>:
663 partInfo.subscripts.emplace_back(hlfir::DesignateOp::Triplet{
664 boundPair.first, boundPair.second, one});
665 auto extentValue = builder.genExtentFromTriplet(
666 loc, boundPair.first, boundPair.second, one, idxTy);
667 resultExtents.push_back(extentValue);
669 // The result shape is: <max((ub - lb + 1) / 1, 0), ...>.
670 partInfo.resultShape = builder.genShape(loc, resultExtents);
671 return componentBaseType;
674 // scalar%array_comp or scalar%scalar. In any case the shape of this
675 // part-ref is coming from the component.
676 partInfo.resultShape = partInfo.componentShape;
677 partInfo.componentShape = {};
678 return componentBaseType;
681 // Returns the <BaseType, ComponentType> pair, computes partInfo.base,
682 // partInfo.componentShape and partInfo.typeParams, but does not set the
683 // partInfo.resultShape yet. The result shape will be computed after
684 // processing a following ArrayRef, if any, and in "visit" otherwise.
685 std::pair<mlir::Type, mlir::Type>
686 visitComponentImpl(const Fortran::evaluate::Component &component,
687 PartInfo &partInfo) {
688 fir::FirOpBuilder &builder = getBuilder();
689 // Break the Designator visit here: if the base is an array-ref, a
690 // coarray-ref, or another component, this creates another hlfir.designate
691 // for it. hlfir.designate is not meant to represent more than one
692 // part-ref.
693 partInfo.base = gen(component.base());
694 // If the base is an allocatable/pointer, dereference it here since the
695 // component ref designates its target.
696 partInfo.base =
697 hlfir::derefPointersAndAllocatables(loc, builder, *partInfo.base);
698 assert(partInfo.typeParams.empty() && "should not have been computed yet");
700 hlfir::genLengthParameters(getLoc(), getBuilder(), *partInfo.base,
701 partInfo.typeParams);
702 mlir::Type baseType = partInfo.base->getElementOrSequenceType();
704 // Lower the information about the component (type, length parameters and
705 // shape).
706 const Fortran::semantics::Symbol &componentSym = component.GetLastSymbol();
707 partInfo.componentName = converter.getRecordTypeFieldName(componentSym);
708 auto recordType =
709 mlir::cast<fir::RecordType>(hlfir::getFortranElementType(baseType));
710 if (recordType.isDependentType())
711 TODO(getLoc(), "Designate derived type with length parameters in HLFIR");
712 mlir::Type fieldType = recordType.getType(partInfo.componentName);
713 assert(fieldType && "component name is not known");
714 mlir::Type fieldBaseType =
715 hlfir::getFortranElementOrSequenceType(fieldType);
716 partInfo.componentShape = genComponentShape(componentSym, fieldBaseType);
718 mlir::Type fieldEleType = hlfir::getFortranElementType(fieldBaseType);
719 if (fir::isRecordWithTypeParameters(fieldEleType))
720 TODO(loc,
721 "lower a component that is a parameterized derived type to HLFIR");
722 if (auto charTy = mlir::dyn_cast<fir::CharacterType>(fieldEleType)) {
723 mlir::Location loc = getLoc();
724 mlir::Type idxTy = builder.getIndexType();
725 if (charTy.hasConstantLen())
726 partInfo.typeParams.push_back(
727 builder.createIntegerConstant(loc, idxTy, charTy.getLen()));
728 else if (!Fortran::semantics::IsAllocatableOrObjectPointer(&componentSym))
729 TODO(loc, "compute character length of automatic character component "
730 "in a PDT");
731 // Otherwise, the length of the component is deferred and will only
732 // be read when the component is dereferenced.
734 return {baseType, fieldType};
737 // Compute: "lb + (i-1)*step".
738 mlir::Value computeTripletPosition(mlir::Location loc,
739 fir::FirOpBuilder &builder,
740 hlfir::DesignateOp::Triplet &triplet,
741 mlir::Value oneBasedIndex) {
742 mlir::Type idxTy = builder.getIndexType();
743 mlir::Value lb = builder.createConvert(loc, idxTy, std::get<0>(triplet));
744 mlir::Value step = builder.createConvert(loc, idxTy, std::get<2>(triplet));
745 mlir::Value one = builder.createIntegerConstant(loc, idxTy, 1);
746 oneBasedIndex = builder.createConvert(loc, idxTy, oneBasedIndex);
747 mlir::Value zeroBased =
748 builder.create<mlir::arith::SubIOp>(loc, oneBasedIndex, one);
749 mlir::Value offset =
750 builder.create<mlir::arith::MulIOp>(loc, zeroBased, step);
751 return builder.create<mlir::arith::AddIOp>(loc, lb, offset);
754 /// Create an hlfir.element_addr operation to deal with vector subscripted
755 /// entities. This transforms the current vector subscripted array-ref into a
756 /// a scalar array-ref that is addressing the vector subscripted part given
757 /// the one based indices of the hlfir.element_addr.
758 /// The rest of the designator lowering will continue lowering any further
759 /// parts inside the hlfir.elemental as a scalar reference.
760 /// At the end of the designator lowering, the hlfir.elemental_addr will
761 /// be turned into an hlfir.elemental value, unless the caller of this
762 /// utility requested to get the hlfir.elemental_addr instead of lowering
763 /// the designator to an mlir::Value.
764 mlir::Type createVectorSubscriptElementAddrOp(
765 PartInfo &partInfo, mlir::Type baseType,
766 llvm::ArrayRef<mlir::Value> resultExtents) {
767 fir::FirOpBuilder &builder = getBuilder();
768 mlir::Value shape = builder.genShape(loc, resultExtents);
769 // The type parameters to be added on the hlfir.elemental_addr are the ones
770 // of the whole designator (not the ones of the vector subscripted part).
771 // These are not yet known and will be added when finalizing the designator
772 // lowering.
773 // The resulting designator may be polymorphic, in which case the resulting
774 // type is the base of the vector subscripted part because
775 // allocatable/pointer components cannot be referenced after a vector
776 // subscripted part. Set the mold to the current base. It will be erased if
777 // the resulting designator is not polymorphic.
778 assert(partInfo.base.has_value() &&
779 "vector subscripted part must have a base");
780 mlir::Value mold = *partInfo.base;
781 auto elementalAddrOp = builder.create<hlfir::ElementalAddrOp>(
782 loc, shape, mold, mlir::ValueRange{},
783 /*isUnordered=*/true);
784 setVectorSubscriptElementAddrOp(elementalAddrOp);
785 builder.setInsertionPointToEnd(&elementalAddrOp.getBody().front());
786 mlir::Region::BlockArgListType indices = elementalAddrOp.getIndices();
787 auto indicesIterator = indices.begin();
788 auto getNextOneBasedIndex = [&]() -> mlir::Value {
789 assert(indicesIterator != indices.end() && "ill formed ElementalAddrOp");
790 return *(indicesIterator++);
792 // Transform the designator into a scalar designator computing the vector
793 // subscripted entity element address given one based indices (for the shape
794 // of the vector subscripted designator).
795 for (hlfir::DesignateOp::Subscript &subscript : partInfo.subscripts) {
796 if (auto *triplet =
797 std::get_if<hlfir::DesignateOp::Triplet>(&subscript)) {
798 // subscript = (lb + (i-1)*step)
799 mlir::Value scalarSubscript = computeTripletPosition(
800 loc, builder, *triplet, getNextOneBasedIndex());
801 subscript = scalarSubscript;
802 } else {
803 hlfir::Entity valueSubscript{std::get<mlir::Value>(subscript)};
804 if (valueSubscript.isScalar())
805 continue;
806 // subscript = vector(i + (vector_lb-1))
807 hlfir::Entity scalarSubscript = hlfir::getElementAt(
808 loc, builder, valueSubscript, {getNextOneBasedIndex()});
809 scalarSubscript =
810 hlfir::loadTrivialScalar(loc, builder, scalarSubscript);
811 subscript = scalarSubscript;
814 builder.setInsertionPoint(elementalAddrOp);
815 return mlir::cast<fir::SequenceType>(baseType).getElementType();
818 /// Yield the designator for the final part-ref inside the
819 /// hlfir.elemental_addr.
820 void finalizeElementAddrOp(hlfir::ElementalAddrOp elementalAddrOp,
821 hlfir::EntityWithAttributes elementAddr) {
822 fir::FirOpBuilder &builder = getBuilder();
823 builder.setInsertionPointToEnd(&elementalAddrOp.getBody().front());
824 if (!elementAddr.isPolymorphic())
825 elementalAddrOp.getMoldMutable().clear();
826 builder.create<hlfir::YieldOp>(loc, elementAddr);
827 builder.setInsertionPointAfter(elementalAddrOp);
830 /// If the lowered designator has vector subscripts turn it into an
831 /// ElementalOp, otherwise, return the lowered designator. This should
832 /// only be called if the user did not request to get the
833 /// hlfir.elemental_addr. In Fortran, vector subscripted designators are only
834 /// writable on the left-hand side of an assignment and in input IO
835 /// statements. Otherwise, they are not variables (cannot be modified, their
836 /// value is taken at the place they appear).
837 hlfir::EntityWithAttributes turnVectorSubscriptedDesignatorIntoValue(
838 hlfir::EntityWithAttributes loweredDesignator) {
839 std::optional<hlfir::ElementalAddrOp> elementalAddrOp =
840 getVectorSubscriptElementAddrOp();
841 if (!elementalAddrOp)
842 return loweredDesignator;
843 finalizeElementAddrOp(*elementalAddrOp, loweredDesignator);
844 // This vector subscript designator is only being read, transform the
845 // hlfir.elemental_addr into an hlfir.elemental. The content of the
846 // hlfir.elemental_addr is cloned, and the resulting address is loaded to
847 // get the new element value.
848 fir::FirOpBuilder &builder = getBuilder();
849 mlir::Location loc = getLoc();
850 mlir::Value elemental =
851 hlfir::cloneToElementalOp(loc, builder, *elementalAddrOp);
852 (*elementalAddrOp)->erase();
853 setVectorSubscriptElementAddrOp(std::nullopt);
854 fir::FirOpBuilder *bldr = &builder;
855 getStmtCtx().attachCleanup(
856 [=]() { bldr->create<hlfir::DestroyOp>(loc, elemental); });
857 return hlfir::EntityWithAttributes{elemental};
860 /// Lower a subscript expression. If it is a scalar subscript that is a
861 /// variable, it is loaded into an integer value. If it is an array (for
862 /// vector subscripts) it is dereferenced if this is an allocatable or
863 /// pointer.
864 template <typename T>
865 hlfir::Entity genSubscript(const Fortran::evaluate::Expr<T> &expr);
867 const std::optional<hlfir::ElementalAddrOp> &
868 getVectorSubscriptElementAddrOp() const {
869 return vectorSubscriptElementAddrOp;
871 void setVectorSubscriptElementAddrOp(
872 std::optional<hlfir::ElementalAddrOp> elementalAddrOp) {
873 vectorSubscriptElementAddrOp = elementalAddrOp;
876 mlir::Location getLoc() const { return loc; }
877 Fortran::lower::AbstractConverter &getConverter() { return converter; }
878 fir::FirOpBuilder &getBuilder() { return converter.getFirOpBuilder(); }
879 Fortran::lower::SymMap &getSymMap() { return symMap; }
880 Fortran::lower::StatementContext &getStmtCtx() { return stmtCtx; }
882 Fortran::lower::AbstractConverter &converter;
883 Fortran::lower::SymMap &symMap;
884 Fortran::lower::StatementContext &stmtCtx;
885 // If there is a vector subscript, an elementalAddrOp is created
886 // to compute the address of the designator elements.
887 std::optional<hlfir::ElementalAddrOp> vectorSubscriptElementAddrOp{};
888 mlir::Location loc;
891 hlfir::EntityWithAttributes HlfirDesignatorBuilder::genDesignatorExpr(
892 const Fortran::lower::SomeExpr &designatorExpr,
893 bool vectorSubscriptDesignatorToValue) {
894 // Expr<SomeType> plumbing to unwrap Designator<T> and call
895 // gen(Designator<T>.u).
896 return Fortran::common::visit(
897 [&](const auto &x) -> hlfir::EntityWithAttributes {
898 using T = std::decay_t<decltype(x)>;
899 if constexpr (Fortran::common::HasMember<
900 T, Fortran::lower::CategoryExpression>) {
901 if constexpr (T::Result::category ==
902 Fortran::common::TypeCategory::Derived) {
903 return gen(std::get<Fortran::evaluate::Designator<
904 Fortran::evaluate::SomeDerived>>(x.u)
906 vectorSubscriptDesignatorToValue);
907 } else {
908 return Fortran::common::visit(
909 [&](const auto &preciseKind) {
910 using TK =
911 typename std::decay_t<decltype(preciseKind)>::Result;
912 return gen(
913 std::get<Fortran::evaluate::Designator<TK>>(preciseKind.u)
915 vectorSubscriptDesignatorToValue);
917 x.u);
919 } else {
920 fir::emitFatalError(loc, "unexpected typeless Designator");
923 designatorExpr.u);
926 hlfir::ElementalAddrOp
927 HlfirDesignatorBuilder::convertVectorSubscriptedExprToElementalAddr(
928 const Fortran::lower::SomeExpr &designatorExpr) {
930 hlfir::EntityWithAttributes elementAddrEntity = genDesignatorExpr(
931 designatorExpr, /*vectorSubscriptDesignatorToValue=*/false);
932 assert(getVectorSubscriptElementAddrOp().has_value() &&
933 "expected vector subscripts");
934 hlfir::ElementalAddrOp elementalAddrOp = *getVectorSubscriptElementAddrOp();
935 // Now that the type parameters have been computed, add then to the
936 // hlfir.elemental_addr.
937 fir::FirOpBuilder &builder = getBuilder();
938 llvm::SmallVector<mlir::Value, 1> lengths;
939 hlfir::genLengthParameters(loc, builder, elementAddrEntity, lengths);
940 if (!lengths.empty())
941 elementalAddrOp.getTypeparamsMutable().assign(lengths);
942 if (!elementAddrEntity.isPolymorphic())
943 elementalAddrOp.getMoldMutable().clear();
944 // Create the hlfir.yield terminator inside the hlfir.elemental_body.
945 builder.setInsertionPointToEnd(&elementalAddrOp.getBody().front());
946 builder.create<hlfir::YieldOp>(loc, elementAddrEntity);
947 builder.setInsertionPointAfter(elementalAddrOp);
948 // Reset the HlfirDesignatorBuilder state, in case it is used on a new
949 // designator.
950 setVectorSubscriptElementAddrOp(std::nullopt);
951 return elementalAddrOp;
954 //===--------------------------------------------------------------------===//
955 // Binary Operation implementation
956 //===--------------------------------------------------------------------===//
958 template <typename T>
959 struct BinaryOp {};
961 #undef GENBIN
962 #define GENBIN(GenBinEvOp, GenBinTyCat, GenBinFirOp) \
963 template <int KIND> \
964 struct BinaryOp<Fortran::evaluate::GenBinEvOp<Fortran::evaluate::Type< \
965 Fortran::common::TypeCategory::GenBinTyCat, KIND>>> { \
966 using Op = Fortran::evaluate::GenBinEvOp<Fortran::evaluate::Type< \
967 Fortran::common::TypeCategory::GenBinTyCat, KIND>>; \
968 static hlfir::EntityWithAttributes gen(mlir::Location loc, \
969 fir::FirOpBuilder &builder, \
970 const Op &, hlfir::Entity lhs, \
971 hlfir::Entity rhs) { \
972 return hlfir::EntityWithAttributes{ \
973 builder.create<GenBinFirOp>(loc, lhs, rhs)}; \
977 GENBIN(Add, Integer, mlir::arith::AddIOp)
978 GENBIN(Add, Real, mlir::arith::AddFOp)
979 GENBIN(Add, Complex, fir::AddcOp)
980 GENBIN(Subtract, Integer, mlir::arith::SubIOp)
981 GENBIN(Subtract, Real, mlir::arith::SubFOp)
982 GENBIN(Subtract, Complex, fir::SubcOp)
983 GENBIN(Multiply, Integer, mlir::arith::MulIOp)
984 GENBIN(Multiply, Real, mlir::arith::MulFOp)
985 GENBIN(Multiply, Complex, fir::MulcOp)
986 GENBIN(Divide, Integer, mlir::arith::DivSIOp)
987 GENBIN(Divide, Real, mlir::arith::DivFOp)
989 template <int KIND>
990 struct BinaryOp<Fortran::evaluate::Divide<
991 Fortran::evaluate::Type<Fortran::common::TypeCategory::Complex, KIND>>> {
992 using Op = Fortran::evaluate::Divide<
993 Fortran::evaluate::Type<Fortran::common::TypeCategory::Complex, KIND>>;
994 static hlfir::EntityWithAttributes gen(mlir::Location loc,
995 fir::FirOpBuilder &builder, const Op &,
996 hlfir::Entity lhs, hlfir::Entity rhs) {
997 mlir::Type ty = Fortran::lower::getFIRType(
998 builder.getContext(), Fortran::common::TypeCategory::Complex, KIND,
999 /*params=*/std::nullopt);
1000 return hlfir::EntityWithAttributes{
1001 fir::genDivC(builder, loc, ty, lhs, rhs)};
1005 template <Fortran::common::TypeCategory TC, int KIND>
1006 struct BinaryOp<Fortran::evaluate::Power<Fortran::evaluate::Type<TC, KIND>>> {
1007 using Op = Fortran::evaluate::Power<Fortran::evaluate::Type<TC, KIND>>;
1008 static hlfir::EntityWithAttributes gen(mlir::Location loc,
1009 fir::FirOpBuilder &builder, const Op &,
1010 hlfir::Entity lhs, hlfir::Entity rhs) {
1011 mlir::Type ty = Fortran::lower::getFIRType(builder.getContext(), TC, KIND,
1012 /*params=*/std::nullopt);
1013 return hlfir::EntityWithAttributes{fir::genPow(builder, loc, ty, lhs, rhs)};
1017 template <Fortran::common::TypeCategory TC, int KIND>
1018 struct BinaryOp<
1019 Fortran::evaluate::RealToIntPower<Fortran::evaluate::Type<TC, KIND>>> {
1020 using Op =
1021 Fortran::evaluate::RealToIntPower<Fortran::evaluate::Type<TC, KIND>>;
1022 static hlfir::EntityWithAttributes gen(mlir::Location loc,
1023 fir::FirOpBuilder &builder, const Op &,
1024 hlfir::Entity lhs, hlfir::Entity rhs) {
1025 mlir::Type ty = Fortran::lower::getFIRType(builder.getContext(), TC, KIND,
1026 /*params=*/std::nullopt);
1027 return hlfir::EntityWithAttributes{fir::genPow(builder, loc, ty, lhs, rhs)};
1031 template <Fortran::common::TypeCategory TC, int KIND>
1032 struct BinaryOp<
1033 Fortran::evaluate::Extremum<Fortran::evaluate::Type<TC, KIND>>> {
1034 using Op = Fortran::evaluate::Extremum<Fortran::evaluate::Type<TC, KIND>>;
1035 static hlfir::EntityWithAttributes gen(mlir::Location loc,
1036 fir::FirOpBuilder &builder,
1037 const Op &op, hlfir::Entity lhs,
1038 hlfir::Entity rhs) {
1039 llvm::SmallVector<mlir::Value, 2> args{lhs, rhs};
1040 fir::ExtendedValue res = op.ordering == Fortran::evaluate::Ordering::Greater
1041 ? fir::genMax(builder, loc, args)
1042 : fir::genMin(builder, loc, args);
1043 return hlfir::EntityWithAttributes{fir::getBase(res)};
1047 // evaluate::Extremum is only created by the front-end when building compiler
1048 // generated expressions (like when folding LEN() or shape/bounds inquiries).
1049 // MIN and MAX are represented as evaluate::ProcedureRef and are not going
1050 // through here. So far the frontend does not generate character Extremum so
1051 // there is no way to test it.
1052 template <int KIND>
1053 struct BinaryOp<Fortran::evaluate::Extremum<
1054 Fortran::evaluate::Type<Fortran::common::TypeCategory::Character, KIND>>> {
1055 using Op = Fortran::evaluate::Extremum<
1056 Fortran::evaluate::Type<Fortran::common::TypeCategory::Character, KIND>>;
1057 static hlfir::EntityWithAttributes gen(mlir::Location loc,
1058 fir::FirOpBuilder &, const Op &,
1059 hlfir::Entity, hlfir::Entity) {
1060 fir::emitFatalError(loc, "Fortran::evaluate::Extremum are unexpected");
1062 static void genResultTypeParams(mlir::Location loc, fir::FirOpBuilder &,
1063 hlfir::Entity, hlfir::Entity,
1064 llvm::SmallVectorImpl<mlir::Value> &) {
1065 fir::emitFatalError(loc, "Fortran::evaluate::Extremum are unexpected");
1069 /// Convert parser's INTEGER relational operators to MLIR.
1070 static mlir::arith::CmpIPredicate
1071 translateRelational(Fortran::common::RelationalOperator rop) {
1072 switch (rop) {
1073 case Fortran::common::RelationalOperator::LT:
1074 return mlir::arith::CmpIPredicate::slt;
1075 case Fortran::common::RelationalOperator::LE:
1076 return mlir::arith::CmpIPredicate::sle;
1077 case Fortran::common::RelationalOperator::EQ:
1078 return mlir::arith::CmpIPredicate::eq;
1079 case Fortran::common::RelationalOperator::NE:
1080 return mlir::arith::CmpIPredicate::ne;
1081 case Fortran::common::RelationalOperator::GT:
1082 return mlir::arith::CmpIPredicate::sgt;
1083 case Fortran::common::RelationalOperator::GE:
1084 return mlir::arith::CmpIPredicate::sge;
1086 llvm_unreachable("unhandled INTEGER relational operator");
1089 /// Convert parser's REAL relational operators to MLIR.
1090 /// The choice of order (O prefix) vs unorder (U prefix) follows Fortran 2018
1091 /// requirements in the IEEE context (table 17.1 of F2018). This choice is
1092 /// also applied in other contexts because it is easier and in line with
1093 /// other Fortran compilers.
1094 /// FIXME: The signaling/quiet aspect of the table 17.1 requirement is not
1095 /// fully enforced. FIR and LLVM `fcmp` instructions do not give any guarantee
1096 /// whether the comparison will signal or not in case of quiet NaN argument.
1097 static mlir::arith::CmpFPredicate
1098 translateFloatRelational(Fortran::common::RelationalOperator rop) {
1099 switch (rop) {
1100 case Fortran::common::RelationalOperator::LT:
1101 return mlir::arith::CmpFPredicate::OLT;
1102 case Fortran::common::RelationalOperator::LE:
1103 return mlir::arith::CmpFPredicate::OLE;
1104 case Fortran::common::RelationalOperator::EQ:
1105 return mlir::arith::CmpFPredicate::OEQ;
1106 case Fortran::common::RelationalOperator::NE:
1107 return mlir::arith::CmpFPredicate::UNE;
1108 case Fortran::common::RelationalOperator::GT:
1109 return mlir::arith::CmpFPredicate::OGT;
1110 case Fortran::common::RelationalOperator::GE:
1111 return mlir::arith::CmpFPredicate::OGE;
1113 llvm_unreachable("unhandled REAL relational operator");
1116 template <int KIND>
1117 struct BinaryOp<Fortran::evaluate::Relational<
1118 Fortran::evaluate::Type<Fortran::common::TypeCategory::Integer, KIND>>> {
1119 using Op = Fortran::evaluate::Relational<
1120 Fortran::evaluate::Type<Fortran::common::TypeCategory::Integer, KIND>>;
1121 static hlfir::EntityWithAttributes gen(mlir::Location loc,
1122 fir::FirOpBuilder &builder,
1123 const Op &op, hlfir::Entity lhs,
1124 hlfir::Entity rhs) {
1125 auto cmp = builder.create<mlir::arith::CmpIOp>(
1126 loc, translateRelational(op.opr), lhs, rhs);
1127 return hlfir::EntityWithAttributes{cmp};
1131 template <int KIND>
1132 struct BinaryOp<Fortran::evaluate::Relational<
1133 Fortran::evaluate::Type<Fortran::common::TypeCategory::Real, KIND>>> {
1134 using Op = Fortran::evaluate::Relational<
1135 Fortran::evaluate::Type<Fortran::common::TypeCategory::Real, KIND>>;
1136 static hlfir::EntityWithAttributes gen(mlir::Location loc,
1137 fir::FirOpBuilder &builder,
1138 const Op &op, hlfir::Entity lhs,
1139 hlfir::Entity rhs) {
1140 auto cmp = builder.create<mlir::arith::CmpFOp>(
1141 loc, translateFloatRelational(op.opr), lhs, rhs);
1142 return hlfir::EntityWithAttributes{cmp};
1146 template <int KIND>
1147 struct BinaryOp<Fortran::evaluate::Relational<
1148 Fortran::evaluate::Type<Fortran::common::TypeCategory::Complex, KIND>>> {
1149 using Op = Fortran::evaluate::Relational<
1150 Fortran::evaluate::Type<Fortran::common::TypeCategory::Complex, KIND>>;
1151 static hlfir::EntityWithAttributes gen(mlir::Location loc,
1152 fir::FirOpBuilder &builder,
1153 const Op &op, hlfir::Entity lhs,
1154 hlfir::Entity rhs) {
1155 auto cmp = builder.create<fir::CmpcOp>(
1156 loc, translateFloatRelational(op.opr), lhs, rhs);
1157 return hlfir::EntityWithAttributes{cmp};
1161 template <int KIND>
1162 struct BinaryOp<Fortran::evaluate::Relational<
1163 Fortran::evaluate::Type<Fortran::common::TypeCategory::Character, KIND>>> {
1164 using Op = Fortran::evaluate::Relational<
1165 Fortran::evaluate::Type<Fortran::common::TypeCategory::Character, KIND>>;
1166 static hlfir::EntityWithAttributes gen(mlir::Location loc,
1167 fir::FirOpBuilder &builder,
1168 const Op &op, hlfir::Entity lhs,
1169 hlfir::Entity rhs) {
1170 auto [lhsExv, lhsCleanUp] =
1171 hlfir::translateToExtendedValue(loc, builder, lhs);
1172 auto [rhsExv, rhsCleanUp] =
1173 hlfir::translateToExtendedValue(loc, builder, rhs);
1174 auto cmp = fir::runtime::genCharCompare(
1175 builder, loc, translateRelational(op.opr), lhsExv, rhsExv);
1176 if (lhsCleanUp)
1177 (*lhsCleanUp)();
1178 if (rhsCleanUp)
1179 (*rhsCleanUp)();
1180 return hlfir::EntityWithAttributes{cmp};
1184 template <int KIND>
1185 struct BinaryOp<Fortran::evaluate::LogicalOperation<KIND>> {
1186 using Op = Fortran::evaluate::LogicalOperation<KIND>;
1187 static hlfir::EntityWithAttributes gen(mlir::Location loc,
1188 fir::FirOpBuilder &builder,
1189 const Op &op, hlfir::Entity lhs,
1190 hlfir::Entity rhs) {
1191 mlir::Type i1Type = builder.getI1Type();
1192 mlir::Value i1Lhs = builder.createConvert(loc, i1Type, lhs);
1193 mlir::Value i1Rhs = builder.createConvert(loc, i1Type, rhs);
1194 switch (op.logicalOperator) {
1195 case Fortran::evaluate::LogicalOperator::And:
1196 return hlfir::EntityWithAttributes{
1197 builder.create<mlir::arith::AndIOp>(loc, i1Lhs, i1Rhs)};
1198 case Fortran::evaluate::LogicalOperator::Or:
1199 return hlfir::EntityWithAttributes{
1200 builder.create<mlir::arith::OrIOp>(loc, i1Lhs, i1Rhs)};
1201 case Fortran::evaluate::LogicalOperator::Eqv:
1202 return hlfir::EntityWithAttributes{builder.create<mlir::arith::CmpIOp>(
1203 loc, mlir::arith::CmpIPredicate::eq, i1Lhs, i1Rhs)};
1204 case Fortran::evaluate::LogicalOperator::Neqv:
1205 return hlfir::EntityWithAttributes{builder.create<mlir::arith::CmpIOp>(
1206 loc, mlir::arith::CmpIPredicate::ne, i1Lhs, i1Rhs)};
1207 case Fortran::evaluate::LogicalOperator::Not:
1208 // lib/evaluate expression for .NOT. is Fortran::evaluate::Not<KIND>.
1209 llvm_unreachable(".NOT. is not a binary operator");
1211 llvm_unreachable("unhandled logical operation");
1215 template <int KIND>
1216 struct BinaryOp<Fortran::evaluate::ComplexConstructor<KIND>> {
1217 using Op = Fortran::evaluate::ComplexConstructor<KIND>;
1218 static hlfir::EntityWithAttributes gen(mlir::Location loc,
1219 fir::FirOpBuilder &builder, const Op &,
1220 hlfir::Entity lhs, hlfir::Entity rhs) {
1221 mlir::Value res =
1222 fir::factory::Complex{builder, loc}.createComplex(lhs, rhs);
1223 return hlfir::EntityWithAttributes{res};
1227 template <int KIND>
1228 struct BinaryOp<Fortran::evaluate::SetLength<KIND>> {
1229 using Op = Fortran::evaluate::SetLength<KIND>;
1230 static hlfir::EntityWithAttributes gen(mlir::Location loc,
1231 fir::FirOpBuilder &builder, const Op &,
1232 hlfir::Entity string,
1233 hlfir::Entity length) {
1234 // The input length may be a user input and needs to be sanitized as per
1235 // Fortran 2018 7.4.4.2 point 5.
1236 mlir::Value safeLength = fir::factory::genMaxWithZero(builder, loc, length);
1237 return hlfir::EntityWithAttributes{
1238 builder.create<hlfir::SetLengthOp>(loc, string, safeLength)};
1240 static void
1241 genResultTypeParams(mlir::Location, fir::FirOpBuilder &, hlfir::Entity,
1242 hlfir::Entity rhs,
1243 llvm::SmallVectorImpl<mlir::Value> &resultTypeParams) {
1244 resultTypeParams.push_back(rhs);
1248 template <int KIND>
1249 struct BinaryOp<Fortran::evaluate::Concat<KIND>> {
1250 using Op = Fortran::evaluate::Concat<KIND>;
1251 hlfir::EntityWithAttributes gen(mlir::Location loc,
1252 fir::FirOpBuilder &builder, const Op &,
1253 hlfir::Entity lhs, hlfir::Entity rhs) {
1254 assert(len && "genResultTypeParams must have been called");
1255 auto concat =
1256 builder.create<hlfir::ConcatOp>(loc, mlir::ValueRange{lhs, rhs}, len);
1257 return hlfir::EntityWithAttributes{concat.getResult()};
1259 void
1260 genResultTypeParams(mlir::Location loc, fir::FirOpBuilder &builder,
1261 hlfir::Entity lhs, hlfir::Entity rhs,
1262 llvm::SmallVectorImpl<mlir::Value> &resultTypeParams) {
1263 llvm::SmallVector<mlir::Value> lengths;
1264 hlfir::genLengthParameters(loc, builder, lhs, lengths);
1265 hlfir::genLengthParameters(loc, builder, rhs, lengths);
1266 assert(lengths.size() == 2 && "lacks rhs or lhs length");
1267 mlir::Type idxType = builder.getIndexType();
1268 mlir::Value lhsLen = builder.createConvert(loc, idxType, lengths[0]);
1269 mlir::Value rhsLen = builder.createConvert(loc, idxType, lengths[1]);
1270 len = builder.create<mlir::arith::AddIOp>(loc, lhsLen, rhsLen);
1271 resultTypeParams.push_back(len);
1274 private:
1275 mlir::Value len{};
1278 //===--------------------------------------------------------------------===//
1279 // Unary Operation implementation
1280 //===--------------------------------------------------------------------===//
1282 template <typename T>
1283 struct UnaryOp {};
1285 template <int KIND>
1286 struct UnaryOp<Fortran::evaluate::Not<KIND>> {
1287 using Op = Fortran::evaluate::Not<KIND>;
1288 static hlfir::EntityWithAttributes gen(mlir::Location loc,
1289 fir::FirOpBuilder &builder, const Op &,
1290 hlfir::Entity lhs) {
1291 mlir::Value one = builder.createBool(loc, true);
1292 mlir::Value val = builder.createConvert(loc, builder.getI1Type(), lhs);
1293 return hlfir::EntityWithAttributes{
1294 builder.create<mlir::arith::XOrIOp>(loc, val, one)};
1298 template <int KIND>
1299 struct UnaryOp<Fortran::evaluate::Negate<
1300 Fortran::evaluate::Type<Fortran::common::TypeCategory::Integer, KIND>>> {
1301 using Op = Fortran::evaluate::Negate<
1302 Fortran::evaluate::Type<Fortran::common::TypeCategory::Integer, KIND>>;
1303 static hlfir::EntityWithAttributes gen(mlir::Location loc,
1304 fir::FirOpBuilder &builder, const Op &,
1305 hlfir::Entity lhs) {
1306 // Like LLVM, integer negation is the binary op "0 - value"
1307 mlir::Type type = Fortran::lower::getFIRType(
1308 builder.getContext(), Fortran::common::TypeCategory::Integer, KIND,
1309 /*params=*/std::nullopt);
1310 mlir::Value zero = builder.createIntegerConstant(loc, type, 0);
1311 return hlfir::EntityWithAttributes{
1312 builder.create<mlir::arith::SubIOp>(loc, zero, lhs)};
1316 template <int KIND>
1317 struct UnaryOp<Fortran::evaluate::Negate<
1318 Fortran::evaluate::Type<Fortran::common::TypeCategory::Real, KIND>>> {
1319 using Op = Fortran::evaluate::Negate<
1320 Fortran::evaluate::Type<Fortran::common::TypeCategory::Real, KIND>>;
1321 static hlfir::EntityWithAttributes gen(mlir::Location loc,
1322 fir::FirOpBuilder &builder, const Op &,
1323 hlfir::Entity lhs) {
1324 return hlfir::EntityWithAttributes{
1325 builder.create<mlir::arith::NegFOp>(loc, lhs)};
1329 template <int KIND>
1330 struct UnaryOp<Fortran::evaluate::Negate<
1331 Fortran::evaluate::Type<Fortran::common::TypeCategory::Complex, KIND>>> {
1332 using Op = Fortran::evaluate::Negate<
1333 Fortran::evaluate::Type<Fortran::common::TypeCategory::Complex, KIND>>;
1334 static hlfir::EntityWithAttributes gen(mlir::Location loc,
1335 fir::FirOpBuilder &builder, const Op &,
1336 hlfir::Entity lhs) {
1337 return hlfir::EntityWithAttributes{builder.create<fir::NegcOp>(loc, lhs)};
1341 template <int KIND>
1342 struct UnaryOp<Fortran::evaluate::ComplexComponent<KIND>> {
1343 using Op = Fortran::evaluate::ComplexComponent<KIND>;
1344 static hlfir::EntityWithAttributes gen(mlir::Location loc,
1345 fir::FirOpBuilder &builder,
1346 const Op &op, hlfir::Entity lhs) {
1347 mlir::Value res = fir::factory::Complex{builder, loc}.extractComplexPart(
1348 lhs, op.isImaginaryPart);
1349 return hlfir::EntityWithAttributes{res};
1353 template <typename T>
1354 struct UnaryOp<Fortran::evaluate::Parentheses<T>> {
1355 using Op = Fortran::evaluate::Parentheses<T>;
1356 static hlfir::EntityWithAttributes gen(mlir::Location loc,
1357 fir::FirOpBuilder &builder,
1358 const Op &op, hlfir::Entity lhs) {
1359 if (lhs.isVariable())
1360 return hlfir::EntityWithAttributes{
1361 builder.create<hlfir::AsExprOp>(loc, lhs)};
1362 return hlfir::EntityWithAttributes{
1363 builder.create<hlfir::NoReassocOp>(loc, lhs.getType(), lhs)};
1366 static void
1367 genResultTypeParams(mlir::Location loc, fir::FirOpBuilder &builder,
1368 hlfir::Entity lhs,
1369 llvm::SmallVectorImpl<mlir::Value> &resultTypeParams) {
1370 hlfir::genLengthParameters(loc, builder, lhs, resultTypeParams);
1374 template <Fortran::common::TypeCategory TC1, int KIND,
1375 Fortran::common::TypeCategory TC2>
1376 struct UnaryOp<
1377 Fortran::evaluate::Convert<Fortran::evaluate::Type<TC1, KIND>, TC2>> {
1378 using Op =
1379 Fortran::evaluate::Convert<Fortran::evaluate::Type<TC1, KIND>, TC2>;
1380 static hlfir::EntityWithAttributes gen(mlir::Location loc,
1381 fir::FirOpBuilder &builder, const Op &,
1382 hlfir::Entity lhs) {
1383 if constexpr (TC1 == Fortran::common::TypeCategory::Character &&
1384 TC2 == TC1) {
1385 return hlfir::convertCharacterKind(loc, builder, lhs, KIND);
1387 mlir::Type type = Fortran::lower::getFIRType(builder.getContext(), TC1,
1388 KIND, /*params=*/std::nullopt);
1389 mlir::Value res = builder.convertWithSemantics(loc, type, lhs);
1390 return hlfir::EntityWithAttributes{res};
1393 static void
1394 genResultTypeParams(mlir::Location loc, fir::FirOpBuilder &builder,
1395 hlfir::Entity lhs,
1396 llvm::SmallVectorImpl<mlir::Value> &resultTypeParams) {
1397 hlfir::genLengthParameters(loc, builder, lhs, resultTypeParams);
1401 static bool hasDeferredCharacterLength(const Fortran::semantics::Symbol &sym) {
1402 const Fortran::semantics::DeclTypeSpec *type = sym.GetType();
1403 return type &&
1404 type->category() ==
1405 Fortran::semantics::DeclTypeSpec::Category::Character &&
1406 type->characterTypeSpec().length().isDeferred();
1409 /// Lower Expr to HLFIR.
1410 class HlfirBuilder {
1411 public:
1412 HlfirBuilder(mlir::Location loc, Fortran::lower::AbstractConverter &converter,
1413 Fortran::lower::SymMap &symMap,
1414 Fortran::lower::StatementContext &stmtCtx)
1415 : converter{converter}, symMap{symMap}, stmtCtx{stmtCtx}, loc{loc} {}
1417 template <typename T>
1418 hlfir::EntityWithAttributes gen(const Fortran::evaluate::Expr<T> &expr) {
1419 if (const Fortran::lower::ExprToValueMap *map =
1420 getConverter().getExprOverrides()) {
1421 if constexpr (std::is_same_v<T, Fortran::evaluate::SomeType>) {
1422 if (auto match = map->find(&expr); match != map->end())
1423 return hlfir::EntityWithAttributes{match->second};
1424 } else {
1425 Fortran::lower::SomeExpr someExpr = toEvExpr(expr);
1426 if (auto match = map->find(&someExpr); match != map->end())
1427 return hlfir::EntityWithAttributes{match->second};
1430 return Fortran::common::visit([&](const auto &x) { return gen(x); },
1431 expr.u);
1434 private:
1435 hlfir::EntityWithAttributes
1436 gen(const Fortran::evaluate::BOZLiteralConstant &expr) {
1437 TODO(getLoc(), "BOZ");
1440 hlfir::EntityWithAttributes gen(const Fortran::evaluate::NullPointer &expr) {
1441 auto nullop = getBuilder().create<hlfir::NullOp>(getLoc());
1442 return mlir::cast<fir::FortranVariableOpInterface>(nullop.getOperation());
1445 hlfir::EntityWithAttributes
1446 gen(const Fortran::evaluate::ProcedureDesignator &proc) {
1447 return Fortran::lower::convertProcedureDesignatorToHLFIR(
1448 getLoc(), getConverter(), proc, getSymMap(), getStmtCtx());
1451 hlfir::EntityWithAttributes gen(const Fortran::evaluate::ProcedureRef &expr) {
1452 Fortran::evaluate::ProcedureDesignator proc{expr.proc()};
1453 auto procTy{Fortran::lower::translateSignature(proc, getConverter())};
1454 auto result = Fortran::lower::convertCallToHLFIR(getLoc(), getConverter(),
1455 expr, procTy.getResult(0),
1456 getSymMap(), getStmtCtx());
1457 assert(result.has_value());
1458 return *result;
1461 template <typename T>
1462 hlfir::EntityWithAttributes
1463 gen(const Fortran::evaluate::Designator<T> &designator) {
1464 return HlfirDesignatorBuilder(getLoc(), getConverter(), getSymMap(),
1465 getStmtCtx())
1466 .gen(designator.u);
1469 template <typename T>
1470 hlfir::EntityWithAttributes
1471 gen(const Fortran::evaluate::FunctionRef<T> &expr) {
1472 mlir::Type resType =
1473 Fortran::lower::TypeBuilder<T>::genType(getConverter(), expr);
1474 auto result = Fortran::lower::convertCallToHLFIR(
1475 getLoc(), getConverter(), expr, resType, getSymMap(), getStmtCtx());
1476 assert(result.has_value());
1477 return *result;
1480 template <typename T>
1481 hlfir::EntityWithAttributes gen(const Fortran::evaluate::Constant<T> &expr) {
1482 mlir::Location loc = getLoc();
1483 fir::FirOpBuilder &builder = getBuilder();
1484 fir::ExtendedValue exv = Fortran::lower::convertConstant(
1485 converter, loc, expr, /*outlineBigConstantInReadOnlyMemory=*/true);
1486 if (const auto *scalarBox = exv.getUnboxed())
1487 if (fir::isa_trivial(scalarBox->getType()))
1488 return hlfir::EntityWithAttributes(*scalarBox);
1489 if (auto addressOf = fir::getBase(exv).getDefiningOp<fir::AddrOfOp>()) {
1490 auto flags = fir::FortranVariableFlagsAttr::get(
1491 builder.getContext(), fir::FortranVariableFlagsEnum::parameter);
1492 return hlfir::genDeclare(
1493 loc, builder, exv,
1494 addressOf.getSymbol().getRootReference().getValue(), flags);
1496 fir::emitFatalError(loc, "Constant<T> was lowered to unexpected format");
1499 template <typename T>
1500 hlfir::EntityWithAttributes
1501 gen(const Fortran::evaluate::ArrayConstructor<T> &arrayCtor) {
1502 return Fortran::lower::ArrayConstructorBuilder<T>::gen(
1503 getLoc(), getConverter(), arrayCtor, getSymMap(), getStmtCtx());
1506 template <typename D, typename R, typename O>
1507 hlfir::EntityWithAttributes
1508 gen(const Fortran::evaluate::Operation<D, R, O> &op) {
1509 auto &builder = getBuilder();
1510 mlir::Location loc = getLoc();
1511 const int rank = op.Rank();
1512 UnaryOp<D> unaryOp;
1513 auto left = hlfir::loadTrivialScalar(loc, builder, gen(op.left()));
1514 llvm::SmallVector<mlir::Value, 1> typeParams;
1515 if constexpr (R::category == Fortran::common::TypeCategory::Character) {
1516 unaryOp.genResultTypeParams(loc, builder, left, typeParams);
1518 if (rank == 0)
1519 return unaryOp.gen(loc, builder, op.derived(), left);
1521 // Elemental expression.
1522 mlir::Type elementType;
1523 if constexpr (R::category == Fortran::common::TypeCategory::Derived) {
1524 if (op.derived().GetType().IsUnlimitedPolymorphic())
1525 elementType = mlir::NoneType::get(builder.getContext());
1526 else
1527 elementType = Fortran::lower::translateDerivedTypeToFIRType(
1528 getConverter(), op.derived().GetType().GetDerivedTypeSpec());
1529 } else {
1530 elementType =
1531 Fortran::lower::getFIRType(builder.getContext(), R::category, R::kind,
1532 /*params=*/std::nullopt);
1534 mlir::Value shape = hlfir::genShape(loc, builder, left);
1535 auto genKernel = [&op, &left, &unaryOp](
1536 mlir::Location l, fir::FirOpBuilder &b,
1537 mlir::ValueRange oneBasedIndices) -> hlfir::Entity {
1538 auto leftElement = hlfir::getElementAt(l, b, left, oneBasedIndices);
1539 auto leftVal = hlfir::loadTrivialScalar(l, b, leftElement);
1540 return unaryOp.gen(l, b, op.derived(), leftVal);
1542 mlir::Value elemental = hlfir::genElementalOp(
1543 loc, builder, elementType, shape, typeParams, genKernel,
1544 /*isUnordered=*/true, left.isPolymorphic() ? left : mlir::Value{});
1545 fir::FirOpBuilder *bldr = &builder;
1546 getStmtCtx().attachCleanup(
1547 [=]() { bldr->create<hlfir::DestroyOp>(loc, elemental); });
1548 return hlfir::EntityWithAttributes{elemental};
1551 template <typename D, typename R, typename LO, typename RO>
1552 hlfir::EntityWithAttributes
1553 gen(const Fortran::evaluate::Operation<D, R, LO, RO> &op) {
1554 auto &builder = getBuilder();
1555 mlir::Location loc = getLoc();
1556 const int rank = op.Rank();
1557 BinaryOp<D> binaryOp;
1558 auto left = hlfir::loadTrivialScalar(loc, builder, gen(op.left()));
1559 auto right = hlfir::loadTrivialScalar(loc, builder, gen(op.right()));
1560 llvm::SmallVector<mlir::Value, 1> typeParams;
1561 if constexpr (R::category == Fortran::common::TypeCategory::Character) {
1562 binaryOp.genResultTypeParams(loc, builder, left, right, typeParams);
1564 if (rank == 0)
1565 return binaryOp.gen(loc, builder, op.derived(), left, right);
1567 // Elemental expression.
1568 mlir::Type elementType =
1569 Fortran::lower::getFIRType(builder.getContext(), R::category, R::kind,
1570 /*params=*/std::nullopt);
1571 // TODO: "merge" shape, get cst shape from front-end if possible.
1572 mlir::Value shape;
1573 if (left.isArray()) {
1574 shape = hlfir::genShape(loc, builder, left);
1575 } else {
1576 assert(right.isArray() && "must have at least one array operand");
1577 shape = hlfir::genShape(loc, builder, right);
1579 auto genKernel = [&op, &left, &right, &binaryOp](
1580 mlir::Location l, fir::FirOpBuilder &b,
1581 mlir::ValueRange oneBasedIndices) -> hlfir::Entity {
1582 auto leftElement = hlfir::getElementAt(l, b, left, oneBasedIndices);
1583 auto rightElement = hlfir::getElementAt(l, b, right, oneBasedIndices);
1584 auto leftVal = hlfir::loadTrivialScalar(l, b, leftElement);
1585 auto rightVal = hlfir::loadTrivialScalar(l, b, rightElement);
1586 return binaryOp.gen(l, b, op.derived(), leftVal, rightVal);
1588 auto iofBackup = builder.getIntegerOverflowFlags();
1589 // nsw is never added to operations on vector subscripts
1590 // even if -fno-wrapv is enabled.
1591 builder.setIntegerOverflowFlags(mlir::arith::IntegerOverflowFlags::none);
1592 mlir::Value elemental = hlfir::genElementalOp(loc, builder, elementType,
1593 shape, typeParams, genKernel,
1594 /*isUnordered=*/true);
1595 builder.setIntegerOverflowFlags(iofBackup);
1596 fir::FirOpBuilder *bldr = &builder;
1597 getStmtCtx().attachCleanup(
1598 [=]() { bldr->create<hlfir::DestroyOp>(loc, elemental); });
1599 return hlfir::EntityWithAttributes{elemental};
1602 hlfir::EntityWithAttributes
1603 gen(const Fortran::evaluate::Relational<Fortran::evaluate::SomeType> &op) {
1604 return Fortran::common::visit([&](const auto &x) { return gen(x); }, op.u);
1607 hlfir::EntityWithAttributes gen(const Fortran::evaluate::TypeParamInquiry &) {
1608 TODO(getLoc(), "lowering type parameter inquiry to HLFIR");
1611 hlfir::EntityWithAttributes
1612 gen(const Fortran::evaluate::DescriptorInquiry &desc) {
1613 mlir::Location loc = getLoc();
1614 auto &builder = getBuilder();
1615 hlfir::EntityWithAttributes entity =
1616 HlfirDesignatorBuilder(getLoc(), getConverter(), getSymMap(),
1617 getStmtCtx())
1618 .genNamedEntity(desc.base());
1619 using ResTy = Fortran::evaluate::DescriptorInquiry::Result;
1620 mlir::Type resultType =
1621 getConverter().genType(ResTy::category, ResTy::kind);
1622 auto castResult = [&](mlir::Value v) {
1623 return hlfir::EntityWithAttributes{
1624 builder.createConvert(loc, resultType, v)};
1626 switch (desc.field()) {
1627 case Fortran::evaluate::DescriptorInquiry::Field::Len:
1628 return castResult(hlfir::genCharLength(loc, builder, entity));
1629 case Fortran::evaluate::DescriptorInquiry::Field::LowerBound:
1630 return castResult(
1631 hlfir::genLBound(loc, builder, entity, desc.dimension()));
1632 case Fortran::evaluate::DescriptorInquiry::Field::Extent:
1633 return castResult(
1634 hlfir::genExtent(loc, builder, entity, desc.dimension()));
1635 case Fortran::evaluate::DescriptorInquiry::Field::Rank:
1636 return castResult(hlfir::genRank(loc, builder, entity, resultType));
1637 case Fortran::evaluate::DescriptorInquiry::Field::Stride:
1638 // So far the front end does not generate this inquiry.
1639 TODO(loc, "stride inquiry");
1641 llvm_unreachable("unknown descriptor inquiry");
1644 hlfir::EntityWithAttributes
1645 gen(const Fortran::evaluate::ImpliedDoIndex &var) {
1646 mlir::Value value = symMap.lookupImpliedDo(toStringRef(var.name));
1647 if (!value)
1648 fir::emitFatalError(getLoc(), "ac-do-variable has no binding");
1649 // The index value generated by the implied-do has Index type,
1650 // while computations based on it inside the loop body are using
1651 // the original data type. So we need to cast it appropriately.
1652 mlir::Type varTy = getConverter().genType(toEvExpr(var));
1653 value = getBuilder().createConvert(getLoc(), varTy, value);
1654 return hlfir::EntityWithAttributes{value};
1657 static bool
1658 isDerivedTypeWithLenParameters(const Fortran::semantics::Symbol &sym) {
1659 if (const Fortran::semantics::DeclTypeSpec *declTy = sym.GetType())
1660 if (const Fortran::semantics::DerivedTypeSpec *derived =
1661 declTy->AsDerived())
1662 return Fortran::semantics::CountLenParameters(*derived) > 0;
1663 return false;
1666 // Construct an entity holding the value specified by the
1667 // StructureConstructor. The initialization of the temporary entity
1668 // is done component by component with the help of HLFIR operations
1669 // DesignateOp and AssignOp.
1670 hlfir::EntityWithAttributes
1671 gen(const Fortran::evaluate::StructureConstructor &ctor) {
1672 mlir::Location loc = getLoc();
1673 fir::FirOpBuilder &builder = getBuilder();
1674 mlir::Type ty = translateSomeExprToFIRType(converter, toEvExpr(ctor));
1675 auto recTy = mlir::cast<fir::RecordType>(ty);
1677 if (recTy.isDependentType())
1678 TODO(loc, "structure constructor for derived type with length parameters "
1679 "in HLFIR");
1681 // Allocate scalar temporary that will be initialized
1682 // with the values specified by the constructor.
1683 mlir::Value storagePtr = builder.createTemporary(loc, recTy);
1684 auto varOp = hlfir::EntityWithAttributes{builder.create<hlfir::DeclareOp>(
1685 loc, storagePtr, "ctor.temp", /*shape=*/nullptr,
1686 /*typeparams=*/mlir::ValueRange{}, /*dummy_scope=*/nullptr,
1687 fir::FortranVariableFlagsAttr{})};
1689 // Initialize any components that need initialization.
1690 mlir::Value box = builder.createBox(loc, fir::ExtendedValue{varOp});
1691 fir::runtime::genDerivedTypeInitialize(builder, loc, box);
1693 // StructureConstructor values may relate to name of components in parent
1694 // types. These components cannot be addressed directly, the parent
1695 // components must be addressed first. The loop below creates all the
1696 // required chains of hlfir.designate to address the parent components so
1697 // that the StructureConstructor can later be lowered by addressing these
1698 // parent components if needed. Note: the front-end orders the components in
1699 // structure constructors. The code below relies on the component to appear
1700 // in order.
1701 using ValueAndParent = std::tuple<const Fortran::lower::SomeExpr &,
1702 const Fortran::semantics::Symbol &,
1703 hlfir::EntityWithAttributes>;
1704 llvm::SmallVector<ValueAndParent> valuesAndParents;
1705 Fortran::lower::ComponentReverseIterator compIterator(
1706 ctor.result().derivedTypeSpec());
1707 hlfir::EntityWithAttributes currentParent = varOp;
1708 for (const auto &value : llvm::reverse(ctor.values())) {
1709 const Fortran::semantics::Symbol &compSym = *value.first;
1710 while (!compIterator.lookup(compSym.name())) {
1711 const auto &parentType = compIterator.advanceToParentType();
1712 llvm::StringRef parentName = toStringRef(parentType.name());
1713 auto baseRecTy = mlir::cast<fir::RecordType>(
1714 hlfir::getFortranElementType(currentParent.getType()));
1715 auto parentCompType = baseRecTy.getType(parentName);
1716 assert(parentCompType && "failed to retrieve parent component type");
1717 mlir::Type designatorType = builder.getRefType(parentCompType);
1718 mlir::Value newParent = builder.create<hlfir::DesignateOp>(
1719 loc, designatorType, currentParent, parentName,
1720 /*compShape=*/mlir::Value{}, hlfir::DesignateOp::Subscripts{},
1721 /*substring=*/mlir::ValueRange{},
1722 /*complexPart=*/std::nullopt,
1723 /*shape=*/mlir::Value{}, /*typeParams=*/mlir::ValueRange{},
1724 fir::FortranVariableFlagsAttr{});
1725 currentParent = hlfir::EntityWithAttributes{newParent};
1727 valuesAndParents.emplace_back(
1728 ValueAndParent{value.second.value(), compSym, currentParent});
1731 HlfirDesignatorBuilder designatorBuilder(loc, converter, symMap, stmtCtx);
1732 for (const auto &iter : llvm::reverse(valuesAndParents)) {
1733 auto &sym = std::get<const Fortran::semantics::Symbol &>(iter);
1734 auto &expr = std::get<const Fortran::lower::SomeExpr &>(iter);
1735 auto &baseOp = std::get<hlfir::EntityWithAttributes>(iter);
1736 std::string name = converter.getRecordTypeFieldName(sym);
1738 // Generate DesignateOp for the component.
1739 // The designator's result type is just a reference to the component type,
1740 // because the whole component is being designated.
1741 auto baseRecTy = mlir::cast<fir::RecordType>(
1742 hlfir::getFortranElementType(baseOp.getType()));
1743 auto compType = baseRecTy.getType(name);
1744 assert(compType && "failed to retrieve component type");
1745 mlir::Value compShape =
1746 designatorBuilder.genComponentShape(sym, compType);
1747 mlir::Type designatorType = builder.getRefType(compType);
1749 mlir::Type fieldElemType = hlfir::getFortranElementType(compType);
1750 llvm::SmallVector<mlir::Value, 1> typeParams;
1751 if (auto charType = mlir::dyn_cast<fir::CharacterType>(fieldElemType)) {
1752 if (charType.hasConstantLen()) {
1753 mlir::Type idxType = builder.getIndexType();
1754 typeParams.push_back(
1755 builder.createIntegerConstant(loc, idxType, charType.getLen()));
1756 } else if (!hasDeferredCharacterLength(sym)) {
1757 // If the length is not deferred, this is a parametrized derived type
1758 // where the character length depends on the derived type length
1759 // parameters. Otherwise, this is a pointer/allocatable component and
1760 // the length will be set during the assignment.
1761 TODO(loc, "automatic character component in structure constructor");
1765 // Convert component symbol attributes to variable attributes.
1766 fir::FortranVariableFlagsAttr attrs =
1767 Fortran::lower::translateSymbolAttributes(builder.getContext(), sym);
1769 // Get the component designator.
1770 auto lhs = builder.create<hlfir::DesignateOp>(
1771 loc, designatorType, baseOp, name, compShape,
1772 hlfir::DesignateOp::Subscripts{},
1773 /*substring=*/mlir::ValueRange{},
1774 /*complexPart=*/std::nullopt,
1775 /*shape=*/compShape, typeParams, attrs);
1777 if (attrs && bitEnumContainsAny(attrs.getFlags(),
1778 fir::FortranVariableFlagsEnum::pointer)) {
1779 if (Fortran::semantics::IsProcedure(sym)) {
1780 // Procedure pointer components.
1781 if (Fortran::evaluate::UnwrapExpr<Fortran::evaluate::NullPointer>(
1782 expr)) {
1783 auto boxTy{
1784 Fortran::lower::getUntypedBoxProcType(builder.getContext())};
1785 hlfir::Entity rhs(
1786 fir::factory::createNullBoxProc(builder, loc, boxTy));
1787 builder.createStoreWithConvert(loc, rhs, lhs);
1788 continue;
1790 hlfir::Entity rhs(getBase(Fortran::lower::convertExprToAddress(
1791 loc, converter, expr, symMap, stmtCtx)));
1792 builder.createStoreWithConvert(loc, rhs, lhs);
1793 continue;
1795 // Pointer component construction is just a copy of the box contents.
1796 fir::ExtendedValue lhsExv =
1797 hlfir::translateToExtendedValue(loc, builder, lhs);
1798 auto *toBox = lhsExv.getBoxOf<fir::MutableBoxValue>();
1799 if (!toBox)
1800 fir::emitFatalError(loc, "pointer component designator could not be "
1801 "lowered to mutable box");
1802 Fortran::lower::associateMutableBox(converter, loc, *toBox, expr,
1803 /*lbounds=*/std::nullopt, stmtCtx);
1804 continue;
1807 // Use generic assignment for all the other cases.
1808 bool allowRealloc =
1809 attrs &&
1810 bitEnumContainsAny(attrs.getFlags(),
1811 fir::FortranVariableFlagsEnum::allocatable);
1812 // If the component is allocatable, then we have to check
1813 // whether the RHS value is allocatable or not.
1814 // If it is not allocatable, then AssignOp can be used directly.
1815 // If it is allocatable, then using AssignOp for unallocated RHS
1816 // will cause illegal dereference. When an unallocated allocatable
1817 // value is used to construct an allocatable component, the component
1818 // must just stay unallocated (see Fortran 2018 7.5.10 point 7).
1820 // If the component is allocatable and RHS is NULL() expression, then
1821 // we can just skip it: the LHS must remain unallocated with its
1822 // defined rank.
1823 if (allowRealloc &&
1824 Fortran::evaluate::UnwrapExpr<Fortran::evaluate::NullPointer>(expr))
1825 continue;
1827 bool keepLhsLength = false;
1828 if (allowRealloc)
1829 if (const Fortran::semantics::DeclTypeSpec *declType = sym.GetType())
1830 keepLhsLength =
1831 declType->category() ==
1832 Fortran::semantics::DeclTypeSpec::Category::Character &&
1833 !declType->characterTypeSpec().length().isDeferred();
1834 // Handle special case when the initializer expression is
1835 // '{%SET_LENGTH(x,const_kind)}'. In structure constructor,
1836 // SET_LENGTH is used for initializers of non-allocatable character
1837 // components so that the front-end can better
1838 // fold and work with these structure constructors.
1839 // Here, they are just noise since the assignment semantics will deal
1840 // with any length mismatch, and creating an extra temp with the lhs
1841 // length is useless.
1842 // TODO: should this be moved into an hlfir.assign + hlfir.set_length
1843 // pattern rewrite?
1844 hlfir::Entity rhs = gen(expr);
1845 if (auto set_length = rhs.getDefiningOp<hlfir::SetLengthOp>())
1846 rhs = hlfir::Entity{set_length.getString()};
1848 // lambda to generate `lhs = rhs` and deal with potential rhs implicit
1849 // cast
1850 auto genAssign = [&] {
1851 rhs = hlfir::loadTrivialScalar(loc, builder, rhs);
1852 auto rhsCastAndCleanup =
1853 hlfir::genTypeAndKindConvert(loc, builder, rhs, lhs.getType(),
1854 /*preserveLowerBounds=*/allowRealloc);
1855 builder.create<hlfir::AssignOp>(loc, rhsCastAndCleanup.first, lhs,
1856 allowRealloc,
1857 allowRealloc ? keepLhsLength : false,
1858 /*temporary_lhs=*/true);
1859 if (rhsCastAndCleanup.second)
1860 (*rhsCastAndCleanup.second)();
1863 if (!allowRealloc || !rhs.isMutableBox()) {
1864 genAssign();
1865 continue;
1868 auto [rhsExv, cleanup] =
1869 hlfir::translateToExtendedValue(loc, builder, rhs);
1870 assert(!cleanup && "unexpected cleanup");
1871 auto *fromBox = rhsExv.getBoxOf<fir::MutableBoxValue>();
1872 if (!fromBox)
1873 fir::emitFatalError(loc, "allocatable entity could not be lowered "
1874 "to mutable box");
1875 mlir::Value isAlloc =
1876 fir::factory::genIsAllocatedOrAssociatedTest(builder, loc, *fromBox);
1877 builder.genIfThen(loc, isAlloc).genThen(genAssign).end();
1880 if (fir::isRecordWithAllocatableMember(recTy)) {
1881 // Deallocate allocatable components without calling final subroutines.
1882 // The Fortran 2018 section 9.7.3.2 about deallocation is not ruling
1883 // about the fate of allocatable components of structure constructors,
1884 // and there is no behavior consensus in other compilers.
1885 fir::FirOpBuilder *bldr = &builder;
1886 getStmtCtx().attachCleanup([=]() {
1887 fir::runtime::genDerivedTypeDestroyWithoutFinalization(*bldr, loc, box);
1890 return varOp;
1893 mlir::Location getLoc() const { return loc; }
1894 Fortran::lower::AbstractConverter &getConverter() { return converter; }
1895 fir::FirOpBuilder &getBuilder() { return converter.getFirOpBuilder(); }
1896 Fortran::lower::SymMap &getSymMap() { return symMap; }
1897 Fortran::lower::StatementContext &getStmtCtx() { return stmtCtx; }
1899 Fortran::lower::AbstractConverter &converter;
1900 Fortran::lower::SymMap &symMap;
1901 Fortran::lower::StatementContext &stmtCtx;
1902 mlir::Location loc;
1905 template <typename T>
1906 hlfir::Entity
1907 HlfirDesignatorBuilder::genSubscript(const Fortran::evaluate::Expr<T> &expr) {
1908 fir::FirOpBuilder &builder = getBuilder();
1909 mlir::arith::IntegerOverflowFlags iofBackup{};
1910 if (!getConverter().getLoweringOptions().getIntegerWrapAround()) {
1911 iofBackup = builder.getIntegerOverflowFlags();
1912 builder.setIntegerOverflowFlags(mlir::arith::IntegerOverflowFlags::nsw);
1914 auto loweredExpr =
1915 HlfirBuilder(getLoc(), getConverter(), getSymMap(), getStmtCtx())
1916 .gen(expr);
1917 if (!getConverter().getLoweringOptions().getIntegerWrapAround())
1918 builder.setIntegerOverflowFlags(iofBackup);
1919 // Skip constant conversions that litters designators and makes generated
1920 // IR harder to read: directly use index constants for constant subscripts.
1921 mlir::Type idxTy = builder.getIndexType();
1922 if (!loweredExpr.isArray() && loweredExpr.getType() != idxTy)
1923 if (auto cstIndex = fir::getIntIfConstant(loweredExpr))
1924 return hlfir::EntityWithAttributes{
1925 builder.createIntegerConstant(getLoc(), idxTy, *cstIndex)};
1926 return hlfir::loadTrivialScalar(loc, builder, loweredExpr);
1929 } // namespace
1931 hlfir::EntityWithAttributes Fortran::lower::convertExprToHLFIR(
1932 mlir::Location loc, Fortran::lower::AbstractConverter &converter,
1933 const Fortran::lower::SomeExpr &expr, Fortran::lower::SymMap &symMap,
1934 Fortran::lower::StatementContext &stmtCtx) {
1935 return HlfirBuilder(loc, converter, symMap, stmtCtx).gen(expr);
1938 fir::ExtendedValue Fortran::lower::convertToBox(
1939 mlir::Location loc, Fortran::lower::AbstractConverter &converter,
1940 hlfir::Entity entity, Fortran::lower::StatementContext &stmtCtx,
1941 mlir::Type fortranType) {
1942 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
1943 auto [exv, cleanup] = hlfir::convertToBox(loc, builder, entity, fortranType);
1944 if (cleanup)
1945 stmtCtx.attachCleanup(*cleanup);
1946 return exv;
1949 fir::ExtendedValue Fortran::lower::convertExprToBox(
1950 mlir::Location loc, Fortran::lower::AbstractConverter &converter,
1951 const Fortran::lower::SomeExpr &expr, Fortran::lower::SymMap &symMap,
1952 Fortran::lower::StatementContext &stmtCtx) {
1953 hlfir::EntityWithAttributes loweredExpr =
1954 HlfirBuilder(loc, converter, symMap, stmtCtx).gen(expr);
1955 return convertToBox(loc, converter, loweredExpr, stmtCtx,
1956 converter.genType(expr));
1959 fir::ExtendedValue Fortran::lower::convertToAddress(
1960 mlir::Location loc, Fortran::lower::AbstractConverter &converter,
1961 hlfir::Entity entity, Fortran::lower::StatementContext &stmtCtx,
1962 mlir::Type fortranType) {
1963 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
1964 auto [exv, cleanup] =
1965 hlfir::convertToAddress(loc, builder, entity, fortranType);
1966 if (cleanup)
1967 stmtCtx.attachCleanup(*cleanup);
1968 return exv;
1971 fir::ExtendedValue Fortran::lower::convertExprToAddress(
1972 mlir::Location loc, Fortran::lower::AbstractConverter &converter,
1973 const Fortran::lower::SomeExpr &expr, Fortran::lower::SymMap &symMap,
1974 Fortran::lower::StatementContext &stmtCtx) {
1975 hlfir::EntityWithAttributes loweredExpr =
1976 HlfirBuilder(loc, converter, symMap, stmtCtx).gen(expr);
1977 return convertToAddress(loc, converter, loweredExpr, stmtCtx,
1978 converter.genType(expr));
1981 fir::ExtendedValue Fortran::lower::convertToValue(
1982 mlir::Location loc, Fortran::lower::AbstractConverter &converter,
1983 hlfir::Entity entity, Fortran::lower::StatementContext &stmtCtx) {
1984 auto &builder = converter.getFirOpBuilder();
1985 auto [exv, cleanup] = hlfir::convertToValue(loc, builder, entity);
1986 if (cleanup)
1987 stmtCtx.attachCleanup(*cleanup);
1988 return exv;
1991 fir::ExtendedValue Fortran::lower::convertExprToValue(
1992 mlir::Location loc, Fortran::lower::AbstractConverter &converter,
1993 const Fortran::lower::SomeExpr &expr, Fortran::lower::SymMap &symMap,
1994 Fortran::lower::StatementContext &stmtCtx) {
1995 hlfir::EntityWithAttributes loweredExpr =
1996 HlfirBuilder(loc, converter, symMap, stmtCtx).gen(expr);
1997 return convertToValue(loc, converter, loweredExpr, stmtCtx);
2000 fir::ExtendedValue Fortran::lower::convertDataRefToValue(
2001 mlir::Location loc, Fortran::lower::AbstractConverter &converter,
2002 const Fortran::evaluate::DataRef &dataRef, Fortran::lower::SymMap &symMap,
2003 Fortran::lower::StatementContext &stmtCtx) {
2004 fir::FortranVariableOpInterface loweredExpr =
2005 HlfirDesignatorBuilder(loc, converter, symMap, stmtCtx).gen(dataRef);
2006 return convertToValue(loc, converter, loweredExpr, stmtCtx);
2009 fir::MutableBoxValue Fortran::lower::convertExprToMutableBox(
2010 mlir::Location loc, Fortran::lower::AbstractConverter &converter,
2011 const Fortran::lower::SomeExpr &expr, Fortran::lower::SymMap &symMap) {
2012 // Pointers and Allocatable cannot be temporary expressions. Temporaries may
2013 // be created while lowering it (e.g. if any indices expression of a
2014 // designator create temporaries), but they can be destroyed before using the
2015 // lowered pointer or allocatable;
2016 Fortran::lower::StatementContext localStmtCtx;
2017 hlfir::EntityWithAttributes loweredExpr =
2018 HlfirBuilder(loc, converter, symMap, localStmtCtx).gen(expr);
2019 fir::ExtendedValue exv = Fortran::lower::translateToExtendedValue(
2020 loc, converter.getFirOpBuilder(), loweredExpr, localStmtCtx);
2021 auto *mutableBox = exv.getBoxOf<fir::MutableBoxValue>();
2022 assert(mutableBox && "expression could not be lowered to mutable box");
2023 return *mutableBox;
2026 hlfir::ElementalAddrOp
2027 Fortran::lower::convertVectorSubscriptedExprToElementalAddr(
2028 mlir::Location loc, Fortran::lower::AbstractConverter &converter,
2029 const Fortran::lower::SomeExpr &designatorExpr,
2030 Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx) {
2031 return HlfirDesignatorBuilder(loc, converter, symMap, stmtCtx)
2032 .convertVectorSubscriptedExprToElementalAddr(designatorExpr);