Debian Codegraph @

flang/lib/Lower/ConvertCall.cpp

raw
1 //===-- ConvertCall.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/Lower/ConvertCall.h"
14 #include "flang/Lower/Allocatable.h"
15 #include "flang/Lower/ConvertExprToHLFIR.h"
16 #include "flang/Lower/ConvertProcedureDesignator.h"
17 #include "flang/Lower/ConvertVariable.h"
18 #include "flang/Lower/CustomIntrinsicCall.h"
19 #include "flang/Lower/HlfirIntrinsics.h"
20 #include "flang/Lower/StatementContext.h"
21 #include "flang/Lower/SymbolMap.h"
22 #include "flang/Optimizer/Builder/BoxValue.h"
23 #include "flang/Optimizer/Builder/Character.h"
24 #include "flang/Optimizer/Builder/FIRBuilder.h"
25 #include "flang/Optimizer/Builder/HLFIRTools.h"
26 #include "flang/Optimizer/Builder/IntrinsicCall.h"
27 #include "flang/Optimizer/Builder/LowLevelIntrinsics.h"
28 #include "flang/Optimizer/Builder/MutableBox.h"
29 #include "flang/Optimizer/Builder/Runtime/Derived.h"
30 #include "flang/Optimizer/Builder/Todo.h"
31 #include "flang/Optimizer/Dialect/CUF/CUFOps.h"
32 #include "flang/Optimizer/Dialect/FIROpsSupport.h"
33 #include "flang/Optimizer/HLFIR/HLFIROps.h"
34 #include "mlir/IR/IRMapping.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include <optional>
38
39 #define DEBUG_TYPE "flang-lower-expr"
40
41 static llvm::cl::opt<bool> useHlfirIntrinsicOps(
42 "use-hlfir-intrinsic-ops", llvm::cl::init(true),
43 llvm::cl::desc("Lower via HLFIR transformational intrinsic operations such "
44 "as hlfir.sum"));
45
46 static constexpr char tempResultName[] = ".tmp.func_result";
47
48 /// Helper to package a Value and its properties into an ExtendedValue.
49 static fir::ExtendedValue toExtendedValue(mlir::Location loc, mlir::Value base,
50 llvm::ArrayRef<mlir::Value> extents,
51 llvm::ArrayRef<mlir::Value> lengths) {
52 mlir::Type type = base.getType();
53 if (mlir::isa<fir::BaseBoxType>(type))
54 return fir::BoxValue(base, /*lbounds=*/{}, lengths, extents);
55 type = fir::unwrapRefType(type);
56 if (mlir::isa<fir::BaseBoxType>(type))
57 return fir::MutableBoxValue(base, lengths, /*mutableProperties*/ {});
58 if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(type)) {
59 if (seqTy.getDimension() != extents.size())
60 fir::emitFatalError(loc, "incorrect number of extents for array");
61 if (mlir::isa<fir::CharacterType>(seqTy.getEleTy())) {
62 if (lengths.empty())
63 fir::emitFatalError(loc, "missing length for character");
64 assert(lengths.size() == 1);
65 return fir::CharArrayBoxValue(base, lengths[0], extents);
66 }
67 return fir::ArrayBoxValue(base, extents);
68 }
69 if (mlir::isa<fir::CharacterType>(type)) {
70 if (lengths.empty())
71 fir::emitFatalError(loc, "missing length for character");
72 assert(lengths.size() == 1);
73 return fir::CharBoxValue(base, lengths[0]);
74 }
75 return base;
76 }
77
78 /// Lower a type(C_PTR/C_FUNPTR) argument with VALUE attribute into a
79 /// reference. A C pointer can correspond to a Fortran dummy argument of type
80 /// C_PTR with the VALUE attribute. (see 18.3.6 note 3).
81 static mlir::Value genRecordCPtrValueArg(fir::FirOpBuilder &builder,
82 mlir::Location loc, mlir::Value rec,
83 mlir::Type ty) {
84 mlir::Value cAddr = fir::factory::genCPtrOrCFunptrAddr(builder, loc, rec, ty);
85 mlir::Value cVal = builder.create<fir::LoadOp>(loc, cAddr);
86 return builder.createConvert(loc, cAddr.getType(), cVal);
87 }
88
89 // Find the argument that corresponds to the host associations.
90 // Verify some assumptions about how the signature was built here.
91 [[maybe_unused]] static unsigned findHostAssocTuplePos(mlir::func::FuncOp fn) {
92 // Scan the argument list from last to first as the host associations are
93 // appended for now.
94 for (unsigned i = fn.getNumArguments(); i > 0; --i)
95 if (fn.getArgAttr(i - 1, fir::getHostAssocAttrName())) {
96 // Host assoc tuple must be last argument (for now).
97 assert(i == fn.getNumArguments() && "tuple must be last");
98 return i - 1;
99 }
100 llvm_unreachable("anyFuncArgsHaveAttr failed");
101 }
102
103 mlir::Value
104 Fortran::lower::argumentHostAssocs(Fortran::lower::AbstractConverter &converter,
105 mlir::Value arg) {
106 if (auto addr = mlir::dyn_cast_or_null<fir::AddrOfOp>(arg.getDefiningOp())) {
107 auto &builder = converter.getFirOpBuilder();
108 if (auto funcOp = builder.getNamedFunction(addr.getSymbol()))
109 if (fir::anyFuncArgsHaveAttr(funcOp, fir::getHostAssocAttrName()))
110 return converter.hostAssocTupleValue();
111 }
112 return {};
113 }
114
115 static bool mustCastFuncOpToCopeWithImplicitInterfaceMismatch(
116 mlir::Location loc, Fortran::lower::AbstractConverter &converter,
117 mlir::FunctionType callSiteType, mlir::FunctionType funcOpType) {
118 // Deal with argument number mismatch by making a function pointer so
119 // that function type cast can be inserted. Do not emit a warning here
120 // because this can happen in legal program if the function is not
121 // defined here and it was first passed as an argument without any more
122 // information.
123 if (callSiteType.getNumResults() != funcOpType.getNumResults() ||
124 callSiteType.getNumInputs() != funcOpType.getNumInputs())
125 return true;
126
127 // Implicit interface result type mismatch are not standard Fortran, but
128 // some compilers are not complaining about it. The front end is not
129 // protecting lowering from this currently. Support this with a
130 // discouraging warning.
131 // Cast the actual function to the current caller implicit type because
132 // that is the behavior we would get if we could not see the definition.
133 if (callSiteType.getResults() != funcOpType.getResults()) {
134 LLVM_DEBUG(mlir::emitWarning(
135 loc, "a return type mismatch is not standard compliant and may "
136 "lead to undefined behavior."));
137 return true;
138 }
139
140 // In HLFIR, there is little attempt to cope with implicit interface
141 // mismatch on the arguments. The argument are always prepared according
142 // to the implicit interface. Cast the actual function if any of the
143 // argument mismatch cannot be dealt with a simple fir.convert.
144 if (converter.getLoweringOptions().getLowerToHighLevelFIR())
145 for (auto [actualType, dummyType] :
146 llvm::zip(callSiteType.getInputs(), funcOpType.getInputs()))
147 if (actualType != dummyType &&
148 !fir::ConvertOp::canBeConverted(actualType, dummyType))
149 return true;
150 return false;
151 }
152
153 static mlir::Value readDim3Value(fir::FirOpBuilder &builder, mlir::Location loc,
154 mlir::Value dim3Addr, llvm::StringRef comp) {
155 mlir::Type i32Ty = builder.getI32Type();
156 mlir::Type refI32Ty = fir::ReferenceType::get(i32Ty);
157 llvm::SmallVector<mlir::Value> lenParams;
158
159 mlir::Value designate = builder.create<hlfir::DesignateOp>(
160 loc, refI32Ty, dim3Addr, /*component=*/comp,
161 /*componentShape=*/mlir::Value{}, hlfir::DesignateOp::Subscripts{},
162 /*substring=*/mlir::ValueRange{}, /*complexPartAttr=*/std::nullopt,
163 mlir::Value{}, lenParams);
164
165 return hlfir::loadTrivialScalar(loc, builder, hlfir::Entity{designate});
166 }
167
168 static mlir::Value remapActualToDummyDescriptor(
169 mlir::Location loc, Fortran::lower::AbstractConverter &converter,
170 Fortran::lower::SymMap &symMap,
171 const Fortran::lower::CallerInterface::PassedEntity &arg,
172 Fortran::lower::CallerInterface &caller, bool isBindcCall) {
173 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
174 mlir::IndexType idxTy = builder.getIndexType();
175 mlir::Value zero = builder.createIntegerConstant(loc, idxTy, 0);
176 Fortran::lower::StatementContext localStmtCtx;
177 auto lowerSpecExpr = [&](const auto &expr,
178 bool isAssumedSizeExtent) -> mlir::Value {
179 mlir::Value convertExpr = builder.createConvert(
180 loc, idxTy, fir::getBase(converter.genExprValue(expr, localStmtCtx)));
181 if (isAssumedSizeExtent)
182 return convertExpr;
183 return fir::factory::genMaxWithZero(builder, loc, convertExpr);
184 };
185 bool mapSymbols = caller.mustMapInterfaceSymbolsForDummyArgument(arg);
186 if (mapSymbols) {
187 symMap.pushScope();
188 const Fortran::semantics::Symbol *sym = caller.getDummySymbol(arg);
189 assert(sym && "call must have explicit interface to map interface symbols");
190 Fortran::lower::mapCallInterfaceSymbolsForDummyArgument(converter, caller,
191 symMap, *sym);
192 }
193 llvm::SmallVector<mlir::Value> extents;
194 llvm::SmallVector<mlir::Value> lengths;
195 mlir::Type dummyBoxType = caller.getDummyArgumentType(arg);
196 mlir::Type dummyBaseType = fir::unwrapPassByRefType(dummyBoxType);
197 if (mlir::isa<fir::SequenceType>(dummyBaseType))
198 caller.walkDummyArgumentExtents(
199 arg, [&](const Fortran::lower::SomeExpr &e, bool isAssumedSizeExtent) {
200 extents.emplace_back(lowerSpecExpr(e, isAssumedSizeExtent));
201 });
202 mlir::Value shape;
203 if (!extents.empty()) {
204 if (isBindcCall) {
205 // Preserve zero lower bounds (see F'2023 18.5.3).
206 llvm::SmallVector<mlir::Value> lowerBounds(extents.size(), zero);
207 shape = builder.genShape(loc, lowerBounds, extents);
208 } else {
209 shape = builder.genShape(loc, extents);
210 }
211 }
212
213 hlfir::Entity explicitArgument = hlfir::Entity{caller.getInput(arg)};
214 mlir::Type dummyElementType = fir::unwrapSequenceType(dummyBaseType);
215 if (auto recType = llvm::dyn_cast<fir::RecordType>(dummyElementType))
216 if (recType.getNumLenParams() > 0)
217 TODO(loc, "sequence association of length parameterized derived type "
218 "dummy arguments");
219 if (fir::isa_char(dummyElementType))
220 lengths.emplace_back(hlfir::genCharLength(loc, builder, explicitArgument));
221 mlir::Value baseAddr =
222 hlfir::genVariableRawAddress(loc, builder, explicitArgument);
223 baseAddr = builder.createConvert(loc, fir::ReferenceType::get(dummyBaseType),
224 baseAddr);
225 mlir::Value mold;
226 if (fir::isPolymorphicType(dummyBoxType))
227 mold = explicitArgument;
228 mlir::Value remapped =
229 builder.create<fir::EmboxOp>(loc, dummyBoxType, baseAddr, shape,
230 /*slice=*/mlir::Value{}, lengths, mold);
231 if (mapSymbols)
232 symMap.popScope();
233 return remapped;
234 }
235
236 /// Create a descriptor for sequenced associated descriptor that are passed
237 /// by descriptor. Sequence association (F'2023 15.5.2.12) implies that the
238 /// dummy shape and rank need to not be the same as the actual argument. This
239 /// helper creates a descriptor based on the dummy shape and rank (sequence
240 /// association can only happen with explicit and assumed-size array) so that it
241 /// is safe to assume the rank of the incoming descriptor inside the callee.
242 /// This helper must be called once all the actual arguments have been lowered
243 /// and placed inside "caller". Copy-in/copy-out must already have been
244 /// generated if needed using the actual argument shape (the dummy shape may be
245 /// assumed-size).
246 static void remapActualToDummyDescriptors(
247 mlir::Location loc, Fortran::lower::AbstractConverter &converter,
248 Fortran::lower::SymMap &symMap,
249 const Fortran::lower::PreparedActualArguments &loweredActuals,
250 Fortran::lower::CallerInterface &caller, bool isBindcCall) {
251 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
252 for (auto [preparedActual, arg] :
253 llvm::zip(loweredActuals, caller.getPassedArguments())) {
254 if (arg.isSequenceAssociatedDescriptor()) {
255 if (!preparedActual.value().handleDynamicOptional()) {
256 mlir::Value remapped = remapActualToDummyDescriptor(
257 loc, converter, symMap, arg, caller, isBindcCall);
258 caller.placeInput(arg, remapped);
259 } else {
260 // Absent optional actual argument descriptor cannot be read and
261 // remapped unconditionally.
262 mlir::Type dummyType = caller.getDummyArgumentType(arg);
263 mlir::Value isPresent = preparedActual.value().getIsPresent();
264 auto &argLambdaCapture = arg;
265 mlir::Value remapped =
266 builder
267 .genIfOp(loc, {dummyType}, isPresent,
268 /*withElseRegion=*/true)
269 .genThen([&]() {
270 mlir::Value newBox = remapActualToDummyDescriptor(
271 loc, converter, symMap, argLambdaCapture, caller,
272 isBindcCall);
273 builder.create<fir::ResultOp>(loc, newBox);
274 })
275 .genElse([&]() {
276 mlir::Value absent =
277 builder.create<fir::AbsentOp>(loc, dummyType);
278 builder.create<fir::ResultOp>(loc, absent);
279 })
280 .getResults()[0];
281 caller.placeInput(arg, remapped);
282 }
283 }
284 }
285 }
286
287 std::pair<fir::ExtendedValue, bool> Fortran::lower::genCallOpAndResult(
288 mlir::Location loc, Fortran::lower::AbstractConverter &converter,
289 Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx,
290 Fortran::lower::CallerInterface &caller, mlir::FunctionType callSiteType,
291 std::optional<mlir::Type> resultType, bool isElemental) {
292 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
293 using PassBy = Fortran::lower::CallerInterface::PassEntityBy;
294 bool mustPopSymMap = false;
295 if (caller.mustMapInterfaceSymbolsForResult()) {
296 symMap.pushScope();
297 mustPopSymMap = true;
298 Fortran::lower::mapCallInterfaceSymbolsForResult(converter, caller, symMap);
299 }
300 // If this is an indirect call, retrieve the function address. Also retrieve
301 // the result length if this is a character function (note that this length
302 // will be used only if there is no explicit length in the local interface).
303 mlir::Value funcPointer;
304 mlir::Value charFuncPointerLength;
305 if (const Fortran::evaluate::ProcedureDesignator *procDesignator =
306 caller.getIfIndirectCall()) {
307 if (mlir::Value passedArg = caller.getIfPassedArg()) {
308 // Procedure pointer component call with PASS argument. To avoid
309 // "double" lowering of the ComponentRef, semantics only place the
310 // ComponentRef in the ActualArguments, not in the ProcedureDesignator (
311 // that is only the component symbol).
312 // Fetch the passed argument and addresses of its procedure pointer
313 // component.
314 funcPointer = Fortran::lower::derefPassProcPointerComponent(
315 loc, converter, *procDesignator, passedArg, symMap, stmtCtx);
316 } else {
317 Fortran::lower::SomeExpr expr{*procDesignator};
318 fir::ExtendedValue loweredProc =
319 converter.genExprAddr(loc, expr, stmtCtx);
320 funcPointer = fir::getBase(loweredProc);
321 // Dummy procedure may have assumed length, in which case the result
322 // length was passed along the dummy procedure.
323 // This is not possible with procedure pointer components.
324 if (const fir::CharBoxValue *charBox = loweredProc.getCharBox())
325 charFuncPointerLength = charBox->getLen();
326 }
327 }
328
329 mlir::IndexType idxTy = builder.getIndexType();
330 auto lowerSpecExpr = [&](const auto &expr) -> mlir::Value {
331 mlir::Value convertExpr = builder.createConvert(
332 loc, idxTy, fir::getBase(converter.genExprValue(expr, stmtCtx)));
333 return fir::factory::genMaxWithZero(builder, loc, convertExpr);
334 };
335 llvm::SmallVector<mlir::Value> resultLengths;
336 auto allocatedResult = [&]() -> std::optional<fir::ExtendedValue> {
337 llvm::SmallVector<mlir::Value> extents;
338 llvm::SmallVector<mlir::Value> lengths;
339 if (!caller.callerAllocateResult())
340 return {};
341 mlir::Type type = caller.getResultStorageType();
342 if (mlir::isa<fir::SequenceType>(type))
343 caller.walkResultExtents(
344 [&](const Fortran::lower::SomeExpr &e, bool isAssumedSizeExtent) {
345 assert(!isAssumedSizeExtent && "result cannot be assumed-size");
346 extents.emplace_back(lowerSpecExpr(e));
347 });
348 caller.walkResultLengths(
349 [&](const Fortran::lower::SomeExpr &e, bool isAssumedSizeExtent) {
350 assert(!isAssumedSizeExtent && "result cannot be assumed-size");
351 lengths.emplace_back(lowerSpecExpr(e));
352 });
353
354 // Result length parameters should not be provided to box storage
355 // allocation and save_results, but they are still useful information to
356 // keep in the ExtendedValue if non-deferred.
357 if (!mlir::isa<fir::BoxType>(type)) {
358 if (fir::isa_char(fir::unwrapSequenceType(type)) && lengths.empty()) {
359 // Calling an assumed length function. This is only possible if this
360 // is a call to a character dummy procedure.
361 if (!charFuncPointerLength)
362 fir::emitFatalError(loc, "failed to retrieve character function "
363 "length while calling it");
364 lengths.push_back(charFuncPointerLength);
365 }
366 resultLengths = lengths;
367 }
368
369 if (!extents.empty() || !lengths.empty()) {
370 auto *bldr = &converter.getFirOpBuilder();
371 auto stackSaveFn = fir::factory::getLlvmStackSave(builder);
372 auto stackSaveSymbol = bldr->getSymbolRefAttr(stackSaveFn.getName());
373 mlir::Value sp;
374 fir::CallOp call = bldr->create<fir::CallOp>(
375 loc, stackSaveFn.getFunctionType().getResults(), stackSaveSymbol,
376 mlir::ValueRange{});
377 if (call.getNumResults() != 0)
378 sp = call.getResult(0);
379 stmtCtx.attachCleanup([bldr, loc, sp]() {
380 auto stackRestoreFn = fir::factory::getLlvmStackRestore(*bldr);
381 auto stackRestoreSymbol =
382 bldr->getSymbolRefAttr(stackRestoreFn.getName());
383 bldr->create<fir::CallOp>(loc,
384 stackRestoreFn.getFunctionType().getResults(),
385 stackRestoreSymbol, mlir::ValueRange{sp});
386 });
387 }
388 mlir::Value temp =
389 builder.createTemporary(loc, type, ".result", extents, resultLengths);
390 return toExtendedValue(loc, temp, extents, lengths);
391 }();
392
393 if (mustPopSymMap)
394 symMap.popScope();
395
396 // Place allocated result or prepare the fir.save_result arguments.
397 mlir::Value arrayResultShape;
398 if (allocatedResult) {
399 if (std::optional<Fortran::lower::CallInterface<
400 Fortran::lower::CallerInterface>::PassedEntity>
401 resultArg = caller.getPassedResult()) {
402 if (resultArg->passBy == PassBy::AddressAndLength)
403 caller.placeAddressAndLengthInput(*resultArg,
404 fir::getBase(*allocatedResult),
405 fir::getLen(*allocatedResult));
406 else if (resultArg->passBy == PassBy::BaseAddress)
407 caller.placeInput(*resultArg, fir::getBase(*allocatedResult));
408 else
409 fir::emitFatalError(
410 loc, "only expect character scalar result to be passed by ref");
411 } else {
412 assert(caller.mustSaveResult());
413 arrayResultShape = allocatedResult->match(
414 [&](const fir::CharArrayBoxValue &) {
415 return builder.createShape(loc, *allocatedResult);
416 },
417 [&](const fir::ArrayBoxValue &) {
418 return builder.createShape(loc, *allocatedResult);
419 },
420 [&](const auto &) { return mlir::Value{}; });
421 }
422 }
423
424 // In older Fortran, procedure argument types are inferred. This may lead
425 // different view of what the function signature is in different locations.
426 // Casts are inserted as needed below to accommodate this.
427
428 // The mlir::func::FuncOp type prevails, unless it has a different number of
429 // arguments which can happen in legal program if it was passed as a dummy
430 // procedure argument earlier with no further type information.
431 mlir::SymbolRefAttr funcSymbolAttr;
432 bool addHostAssociations = false;
433 if (!funcPointer) {
434 mlir::FunctionType funcOpType = caller.getFuncOp().getFunctionType();
435 mlir::SymbolRefAttr symbolAttr =
436 builder.getSymbolRefAttr(caller.getMangledName());
437 if (callSiteType.getNumResults() == funcOpType.getNumResults() &&
438 callSiteType.getNumInputs() + 1 == funcOpType.getNumInputs() &&
439 fir::anyFuncArgsHaveAttr(caller.getFuncOp(),
440 fir::getHostAssocAttrName())) {
441 // The number of arguments is off by one, and we're lowering a function
442 // with host associations. Modify call to include host associations
443 // argument by appending the value at the end of the operands.
444 assert(funcOpType.getInput(findHostAssocTuplePos(caller.getFuncOp())) ==
445 converter.hostAssocTupleValue().getType());
446 addHostAssociations = true;
447 }
448 // When this is not a call to an internal procedure (where there is a
449 // mismatch due to the extra argument, but the interface is otherwise
450 // explicit and safe), handle interface mismatch due to F77 implicit
451 // interface "abuse" with a function address cast if needed.
452 if (!addHostAssociations &&
453 mustCastFuncOpToCopeWithImplicitInterfaceMismatch(
454 loc, converter, callSiteType, funcOpType))
455 funcPointer = builder.create<fir::AddrOfOp>(loc, funcOpType, symbolAttr);
456 else
457 funcSymbolAttr = symbolAttr;
458
459 // Issue a warning if the procedure name conflicts with
460 // a runtime function name a call to which has been already
461 // lowered (implying that the FuncOp has been created).
462 // The behavior is undefined in this case.
463 if (caller.getFuncOp()->hasAttrOfType<mlir::UnitAttr>(
464 fir::FIROpsDialect::getFirRuntimeAttrName()))
465 LLVM_DEBUG(mlir::emitWarning(
466 loc,
467 llvm::Twine("function name '") +
468 llvm::Twine(symbolAttr.getLeafReference()) +
469 llvm::Twine("' conflicts with a runtime function name used by "
470 "Flang - this may lead to undefined behavior")));
471 }
472
473 mlir::FunctionType funcType =
474 funcPointer ? callSiteType : caller.getFuncOp().getFunctionType();
475 llvm::SmallVector<mlir::Value> operands;
476 // First operand of indirect call is the function pointer. Cast it to
477 // required function type for the call to handle procedures that have a
478 // compatible interface in Fortran, but that have different signatures in
479 // FIR.
480 if (funcPointer) {
481 operands.push_back(
482 mlir::isa<fir::BoxProcType>(funcPointer.getType())
483 ? builder.create<fir::BoxAddrOp>(loc, funcType, funcPointer)
484 : builder.createConvert(loc, funcType, funcPointer));
485 }
486
487 // Deal with potential mismatches in arguments types. Passing an array to a
488 // scalar argument should for instance be tolerated here.
489 bool callingImplicitInterface = caller.canBeCalledViaImplicitInterface();
490 for (auto [fst, snd] : llvm::zip(caller.getInputs(), funcType.getInputs())) {
491 // When passing arguments to a procedure that can be called by implicit
492 // interface, allow any character actual arguments to be passed to dummy
493 // arguments of any type and vice versa.
494 mlir::Value cast;
495 auto *context = builder.getContext();
496 if (mlir::isa<fir::BoxProcType>(snd) &&
497 mlir::isa<mlir::FunctionType>(fst.getType())) {
498 auto funcTy =
499 mlir::FunctionType::get(context, std::nullopt, std::nullopt);
500 auto boxProcTy = builder.getBoxProcType(funcTy);
501 if (mlir::Value host = argumentHostAssocs(converter, fst)) {
502 cast = builder.create<fir::EmboxProcOp>(
503 loc, boxProcTy, llvm::ArrayRef<mlir::Value>{fst, host});
504 } else {
505 cast = builder.create<fir::EmboxProcOp>(loc, boxProcTy, fst);
506 }
507 } else {
508 mlir::Type fromTy = fir::unwrapRefType(fst.getType());
509 if (fir::isa_builtin_cptr_type(fromTy) &&
510 Fortran::lower::isCPtrArgByValueType(snd)) {
511 cast = genRecordCPtrValueArg(builder, loc, fst, fromTy);
512 } else if (fir::isa_derived(snd) && !fir::isa_derived(fst.getType())) {
513 // TODO: remove this TODO once the old lowering is gone.
514 TODO(loc, "derived type argument passed by value");
515 } else {
516 // With the lowering to HLFIR, box arguments have already been built
517 // according to the attributes, rank, bounds, and type they should have.
518 // Do not attempt any reboxing here that could break this.
519 bool legacyLowering =
520 !converter.getLoweringOptions().getLowerToHighLevelFIR();
521 cast = builder.convertWithSemantics(loc, snd, fst,
522 callingImplicitInterface,
523 /*allowRebox=*/legacyLowering);
524 }
525 }
526 operands.push_back(cast);
527 }
528
529 // Add host associations as necessary.
530 if (addHostAssociations)
531 operands.push_back(converter.hostAssocTupleValue());
532
533 mlir::Value callResult;
534 unsigned callNumResults;
535
536 if (!caller.getCallDescription().chevrons().empty()) {
537 // A call to a CUDA kernel with the chevron syntax.
538
539 mlir::Type i32Ty = builder.getI32Type();
540 mlir::Value one = builder.createIntegerConstant(loc, i32Ty, 1);
541
542 mlir::Value grid_x, grid_y, grid_z;
543 if (caller.getCallDescription().chevrons()[0].GetType()->category() ==
544 Fortran::common::TypeCategory::Integer) {
545 // If grid is an integer, it is converted to dim3(grid,1,1). Since z is
546 // not used for the number of thread blocks, it is omitted in the op.
547 grid_x = builder.createConvert(
548 loc, i32Ty,
549 fir::getBase(converter.genExprValue(
550 caller.getCallDescription().chevrons()[0], stmtCtx)));
551 grid_y = one;
552 grid_z = one;
553 } else {
554 auto dim3Addr = converter.genExprAddr(
555 caller.getCallDescription().chevrons()[0], stmtCtx);
556 grid_x = readDim3Value(builder, loc, fir::getBase(dim3Addr), "x");
557 grid_y = readDim3Value(builder, loc, fir::getBase(dim3Addr), "y");
558 grid_z = readDim3Value(builder, loc, fir::getBase(dim3Addr), "z");
559 }
560
561 mlir::Value block_x, block_y, block_z;
562 if (caller.getCallDescription().chevrons()[1].GetType()->category() ==
563 Fortran::common::TypeCategory::Integer) {
564 // If block is an integer, it is converted to dim3(block,1,1).
565 block_x = builder.createConvert(
566 loc, i32Ty,
567 fir::getBase(converter.genExprValue(
568 caller.getCallDescription().chevrons()[1], stmtCtx)));
569 block_y = one;
570 block_z = one;
571 } else {
572 auto dim3Addr = converter.genExprAddr(
573 caller.getCallDescription().chevrons()[1], stmtCtx);
574 block_x = readDim3Value(builder, loc, fir::getBase(dim3Addr), "x");
575 block_y = readDim3Value(builder, loc, fir::getBase(dim3Addr), "y");
576 block_z = readDim3Value(builder, loc, fir::getBase(dim3Addr), "z");
577 }
578
579 mlir::Value bytes; // bytes is optional.
580 if (caller.getCallDescription().chevrons().size() > 2)
581 bytes = builder.createConvert(
582 loc, i32Ty,
583 fir::getBase(converter.genExprValue(
584 caller.getCallDescription().chevrons()[2], stmtCtx)));
585
586 mlir::Value stream; // stream is optional.
587 if (caller.getCallDescription().chevrons().size() > 3)
588 stream = builder.createConvert(
589 loc, i32Ty,
590 fir::getBase(converter.genExprValue(
591 caller.getCallDescription().chevrons()[3], stmtCtx)));
592
593 builder.create<cuf::KernelLaunchOp>(
594 loc, funcType.getResults(), funcSymbolAttr, grid_x, grid_y, grid_z,
595 block_x, block_y, block_z, bytes, stream, operands);
596 callNumResults = 0;
597 } else if (caller.requireDispatchCall()) {
598 // Procedure call requiring a dynamic dispatch. Call is created with
599 // fir.dispatch.
600
601 // Get the raw procedure name. The procedure name is not mangled in the
602 // binding table, but there can be a suffix to distinguish bindings of
603 // the same name (which happens only when PRIVATE bindings exist in
604 // ancestor types in other modules).
605 const auto &ultimateSymbol =
606 caller.getCallDescription().proc().GetSymbol()->GetUltimate();
607 std::string procName = ultimateSymbol.name().ToString();
608 if (const auto &binding{
609 ultimateSymbol.get<Fortran::semantics::ProcBindingDetails>()};
610 binding.numPrivatesNotOverridden() > 0)
611 procName += "."s + std::to_string(binding.numPrivatesNotOverridden());
612 fir::DispatchOp dispatch;
613 if (std::optional<unsigned> passArg = caller.getPassArgIndex()) {
614 // PASS, PASS(arg-name)
615 // Note that caller.getInputs is used instead of operands to get the
616 // passed object because interface mismatch issues may have inserted a
617 // cast to the operand with a different declared type, which would break
618 // later type bound call resolution in the FIR to FIR pass.
619 dispatch = builder.create<fir::DispatchOp>(
620 loc, funcType.getResults(), builder.getStringAttr(procName),
621 caller.getInputs()[*passArg], operands,
622 builder.getI32IntegerAttr(*passArg));
623 } else {
624 // NOPASS
625 const Fortran::evaluate::Component *component =
626 caller.getCallDescription().proc().GetComponent();
627 assert(component && "expect component for type-bound procedure call.");
628
629 fir::ExtendedValue dataRefValue = Fortran::lower::convertDataRefToValue(
630 loc, converter, component->base(), symMap, stmtCtx);
631 mlir::Value passObject = fir::getBase(dataRefValue);
632
633 if (fir::isa_ref_type(passObject.getType()))
634 passObject = builder.create<fir::LoadOp>(loc, passObject);
635 dispatch = builder.create<fir::DispatchOp>(
636 loc, funcType.getResults(), builder.getStringAttr(procName),
637 passObject, operands, nullptr);
638 }
639 callNumResults = dispatch.getNumResults();
640 if (callNumResults != 0)
641 callResult = dispatch.getResult(0);
642 } else {
643 // Standard procedure call with fir.call.
644 auto call = builder.create<fir::CallOp>(loc, funcType.getResults(),
645 funcSymbolAttr, operands);
646 if (caller.characterize().IsBindC())
647 call.setIsBindC(true);
648
649 callNumResults = call.getNumResults();
650 if (callNumResults != 0)
651 callResult = call.getResult(0);
652 }
653
654 if (caller.mustSaveResult()) {
655 assert(allocatedResult.has_value());
656 builder.create<fir::SaveResultOp>(loc, callResult,
657 fir::getBase(*allocatedResult),
658 arrayResultShape, resultLengths);
659 }
660
661 if (allocatedResult) {
662 // The result must be optionally destroyed (if it is of a derived type
663 // that may need finalization or deallocation of the components).
664 // For an allocatable result we have to free the memory allocated
665 // for the top-level entity. Note that the Destroy calls below
666 // do not deallocate the top-level entity. The two clean-ups
667 // must be pushed in reverse order, so that the final order is:
668 // Destroy(desc)
669 // free(desc->base_addr)
670 allocatedResult->match(
671 [&](const fir::MutableBoxValue &box) {
672 if (box.isAllocatable()) {
673 // 9.7.3.2 point 4. Deallocate allocatable results. Note that
674 // finalization was done independently by calling
675 // genDerivedTypeDestroy above and is not triggered by this inline
676 // deallocation.
677 fir::FirOpBuilder *bldr = &converter.getFirOpBuilder();
678 stmtCtx.attachCleanup([bldr, loc, box]() {
679 fir::factory::genFreememIfAllocated(*bldr, loc, box);
680 });
681 }
682 },
683 [](const auto &) {});
684
685 // 7.5.6.3 point 5. Derived-type finalization for nonpointer function.
686 bool resultIsFinalized = false;
687 // Check if the derived-type is finalizable if it is a monomorphic
688 // derived-type.
689 // For polymorphic and unlimited polymorphic enities call the runtime
690 // in any cases.
691 std::optional<Fortran::evaluate::DynamicType> retTy =
692 caller.getCallDescription().proc().GetType();
693 // With HLFIR lowering, isElemental must be set to true
694 // if we are producing an elemental call. In this case,
695 // the elemental results must not be destroyed, instead,
696 // the resulting array result will be finalized/destroyed
697 // as needed by hlfir.destroy.
698 if (!isElemental && !fir::isPointerType(funcType.getResults()[0]) &&
699 retTy &&
700 (retTy->category() == Fortran::common::TypeCategory::Derived ||
701 retTy->IsPolymorphic() || retTy->IsUnlimitedPolymorphic())) {
702 if (retTy->IsPolymorphic() || retTy->IsUnlimitedPolymorphic()) {
703 auto *bldr = &converter.getFirOpBuilder();
704 stmtCtx.attachCleanup([bldr, loc, allocatedResult]() {
705 fir::runtime::genDerivedTypeDestroy(*bldr, loc,
706 fir::getBase(*allocatedResult));
707 });
708 resultIsFinalized = true;
709 } else {
710 const Fortran::semantics::DerivedTypeSpec &typeSpec =
711 retTy->GetDerivedTypeSpec();
712 // If the result type may require finalization
713 // or have allocatable components, we need to make sure
714 // everything is properly finalized/deallocated.
715 if (Fortran::semantics::MayRequireFinalization(typeSpec) ||
716 // We can use DerivedTypeDestroy even if finalization is not needed.
717 hlfir::mayHaveAllocatableComponent(funcType.getResults()[0])) {
718 auto *bldr = &converter.getFirOpBuilder();
719 stmtCtx.attachCleanup([bldr, loc, allocatedResult]() {
720 mlir::Value box = bldr->createBox(loc, *allocatedResult);
721 fir::runtime::genDerivedTypeDestroy(*bldr, loc, box);
722 });
723 resultIsFinalized = true;
724 }
725 }
726 }
727 return {*allocatedResult, resultIsFinalized};
728 }
729
730 // subroutine call
731 if (!resultType)
732 return {fir::ExtendedValue{mlir::Value{}}, /*resultIsFinalized=*/false};
733
734 // For now, Fortran return values are implemented with a single MLIR
735 // function return value.
736 assert(callNumResults == 1 && "Expected exactly one result in FUNCTION call");
737 (void)callNumResults;
738
739 // Call a BIND(C) function that return a char.
740 if (caller.characterize().IsBindC() &&
741 mlir::isa<fir::CharacterType>(funcType.getResults()[0])) {
742 fir::CharacterType charTy =
743 mlir::dyn_cast<fir::CharacterType>(funcType.getResults()[0]);
744 mlir::Value len = builder.createIntegerConstant(
745 loc, builder.getCharacterLengthType(), charTy.getLen());
746 return {fir::CharBoxValue{callResult, len}, /*resultIsFinalized=*/false};
747 }
748
749 return {callResult, /*resultIsFinalized=*/false};
750 }
751
752 static hlfir::EntityWithAttributes genStmtFunctionRef(
753 mlir::Location loc, Fortran::lower::AbstractConverter &converter,
754 Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx,
755 const Fortran::evaluate::ProcedureRef &procRef) {
756 const Fortran::semantics::Symbol *symbol = procRef.proc().GetSymbol();
757 assert(symbol && "expected symbol in ProcedureRef of statement functions");
758 const auto &details = symbol->get<Fortran::semantics::SubprogramDetails>();
759 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
760
761 // Statement functions have their own scope, we just need to associate
762 // the dummy symbols to argument expressions. There are no
763 // optional/alternate return arguments. Statement functions cannot be
764 // recursive (directly or indirectly) so it is safe to add dummy symbols to
765 // the local map here.
766 symMap.pushScope();
767 llvm::SmallVector<hlfir::AssociateOp> exprAssociations;
768 for (auto [arg, bind] : llvm::zip(details.dummyArgs(), procRef.arguments())) {
769 assert(arg && "alternate return in statement function");
770 assert(bind && "optional argument in statement function");
771 const auto *expr = bind->UnwrapExpr();
772 // TODO: assumed type in statement function, that surprisingly seems
773 // allowed, probably because nobody thought of restricting this usage.
774 // gfortran/ifort compiles this.
775 assert(expr && "assumed type used as statement function argument");
776 // As per Fortran 2018 C1580, statement function arguments can only be
777 // scalars.
778 // The only care is to use the dummy character explicit length if any
779 // instead of the actual argument length (that can be bigger).
780 hlfir::EntityWithAttributes loweredArg = Fortran::lower::convertExprToHLFIR(
781 loc, converter, *expr, symMap, stmtCtx);
782 fir::FortranVariableOpInterface variableIface = loweredArg.getIfVariable();
783 if (!variableIface) {
784 // So far only FortranVariableOpInterface can be mapped to symbols.
785 // Create an hlfir.associate to create a variable from a potential
786 // value argument.
787 mlir::Type argType = converter.genType(*arg);
788 auto associate = hlfir::genAssociateExpr(
789 loc, builder, loweredArg, argType, toStringRef(arg->name()));
790 exprAssociations.push_back(associate);
791 variableIface = associate;
792 }
793 const Fortran::semantics::DeclTypeSpec *type = arg->GetType();
794 if (type &&
795 type->category() == Fortran::semantics::DeclTypeSpec::Character) {
796 // Instantiate character as if it was a normal dummy argument so that the
797 // statement function dummy character length is applied and dealt with
798 // correctly.
799 symMap.addSymbol(*arg, variableIface.getBase());
800 Fortran::lower::mapSymbolAttributes(converter, *arg, symMap, stmtCtx);
801 } else {
802 // No need to create an extra hlfir.declare otherwise for
803 // numerical and logical scalar dummies.
804 symMap.addVariableDefinition(*arg, variableIface);
805 }
806 }
807
808 // Explicitly map statement function host associated symbols to their
809 // parent scope lowered symbol box.
810 for (const Fortran::semantics::SymbolRef &sym :
811 Fortran::evaluate::CollectSymbols(*details.stmtFunction()))
812 if (const auto *details =
813 sym->detailsIf<Fortran::semantics::HostAssocDetails>())
814 converter.copySymbolBinding(details->symbol(), sym);
815
816 hlfir::Entity result = Fortran::lower::convertExprToHLFIR(
817 loc, converter, details.stmtFunction().value(), symMap, stmtCtx);
818 symMap.popScope();
819 // The result must not be a variable.
820 result = hlfir::loadTrivialScalar(loc, builder, result);
821 if (result.isVariable())
822 result = hlfir::Entity{builder.create<hlfir::AsExprOp>(loc, result)};
823 for (auto associate : exprAssociations)
824 builder.create<hlfir::EndAssociateOp>(loc, associate);
825 return hlfir::EntityWithAttributes{result};
826 }
827
828 namespace {
829 // Structure to hold the information about the call and the lowering context.
830 // This structure is intended to help threading the information
831 // through the various lowering calls without having to pass every
832 // required structure one by one.
833 struct CallContext {
834 CallContext(const Fortran::evaluate::ProcedureRef &procRef,
835 std::optional<mlir::Type> resultType, mlir::Location loc,
836 Fortran::lower::AbstractConverter &converter,
837 Fortran::lower::SymMap &symMap,
838 Fortran::lower::StatementContext &stmtCtx)
839 : procRef{procRef}, converter{converter}, symMap{symMap},
840 stmtCtx{stmtCtx}, resultType{resultType}, loc{loc} {}
841
842 fir::FirOpBuilder &getBuilder() { return converter.getFirOpBuilder(); }
843
844 std::string getProcedureName() const {
845 if (const Fortran::semantics::Symbol *sym = procRef.proc().GetSymbol())
846 return sym->GetUltimate().name().ToString();
847 return procRef.proc().GetName();
848 }
849
850 /// Is this a call to an elemental procedure with at least one array argument?
851 bool isElementalProcWithArrayArgs() const {
852 if (procRef.IsElemental())
853 for (const std::optional<Fortran::evaluate::ActualArgument> &arg :
854 procRef.arguments())
855 if (arg && arg->Rank() != 0)
856 return true;
857 return false;
858 }
859
860 /// Is this a statement function reference?
861 bool isStatementFunctionCall() const {
862 if (const Fortran::semantics::Symbol *symbol = procRef.proc().GetSymbol())
863 if (const auto *details =
864 symbol->detailsIf<Fortran::semantics::SubprogramDetails>())
865 return details->stmtFunction().has_value();
866 return false;
867 }
868
869 /// Is this a call to a BIND(C) procedure?
870 bool isBindcCall() const {
871 if (const Fortran::semantics::Symbol *symbol = procRef.proc().GetSymbol())
872 return Fortran::semantics::IsBindCProcedure(*symbol);
873 return false;
874 }
875
876 const Fortran::evaluate::ProcedureRef &procRef;
877 Fortran::lower::AbstractConverter &converter;
878 Fortran::lower::SymMap &symMap;
879 Fortran::lower::StatementContext &stmtCtx;
880 std::optional<mlir::Type> resultType;
881 mlir::Location loc;
882 };
883
884 using ExvAndCleanup =
885 std::pair<fir::ExtendedValue, std::optional<hlfir::CleanupFunction>>;
886 } // namespace
887
888 // Helper to transform a fir::ExtendedValue to an hlfir::EntityWithAttributes.
889 static hlfir::EntityWithAttributes
890 extendedValueToHlfirEntity(mlir::Location loc, fir::FirOpBuilder &builder,
891 const fir::ExtendedValue &exv,
892 llvm::StringRef name) {
893 mlir::Value firBase = fir::getBase(exv);
894 mlir::Type firBaseTy = firBase.getType();
895 if (fir::isa_trivial(firBaseTy))
896 return hlfir::EntityWithAttributes{firBase};
897 if (auto charTy = mlir::dyn_cast<fir::CharacterType>(firBase.getType())) {
898 // CHAR() intrinsic and BIND(C) procedures returning CHARACTER(1)
899 // are lowered to a fir.char<kind,1> that is not in memory.
900 // This tends to cause a lot of bugs because the rest of the
901 // infrastructure is mostly tested with characters that are
902 // in memory.
903 // To avoid having to deal with this special case here and there,
904 // place it in memory here. If this turns out to be suboptimal,
905 // this could be fixed, but for now llvm opt -O1 is able to get
906 // rid of the memory indirection in a = char(b), so there is
907 // little incentive to increase the compiler complexity.
908 hlfir::Entity storage{builder.createTemporary(loc, charTy)};
909 builder.create<fir::StoreOp>(loc, firBase, storage);
910 auto asExpr = builder.create<hlfir::AsExprOp>(
911 loc, storage, /*mustFree=*/builder.createBool(loc, false));
912 return hlfir::EntityWithAttributes{asExpr.getResult()};
913 }
914 return hlfir::genDeclare(loc, builder, exv, name,
915 fir::FortranVariableFlagsAttr{});
916 }
917 namespace {
918 /// Structure to hold the clean-up related to a dummy argument preparation
919 /// that may have to be done after a call (copy-out or temporary deallocation).
920 struct CallCleanUp {
921 struct CopyIn {
922 void genCleanUp(mlir::Location loc, fir::FirOpBuilder &builder) {
923 builder.create<hlfir::CopyOutOp>(loc, tempBox, wasCopied, copyBackVar);
924 }
925 // address of the descriptor holding the temp if a temp was created.
926 mlir::Value tempBox;
927 // Boolean indicating if a copy was made or not.
928 mlir::Value wasCopied;
929 // copyBackVar may be null if copy back is not needed.
930 mlir::Value copyBackVar;
931 };
932 struct ExprAssociate {
933 void genCleanUp(mlir::Location loc, fir::FirOpBuilder &builder) {
934 builder.create<hlfir::EndAssociateOp>(loc, tempVar, mustFree);
935 }
936 mlir::Value tempVar;
937 mlir::Value mustFree;
938 };
939 void genCleanUp(mlir::Location loc, fir::FirOpBuilder &builder) {
940 Fortran::common::visit([&](auto &c) { c.genCleanUp(loc, builder); },
941 cleanUp);
942 }
943 std::variant<CopyIn, ExprAssociate> cleanUp;
944 };
945
946 /// Structure representing a prepared dummy argument.
947 /// It holds the value to be passed in the call and any related
948 /// clean-ups to be done after the call.
949 struct PreparedDummyArgument {
950 void pushCopyInCleanUp(mlir::Value tempBox, mlir::Value wasCopied,
951 mlir::Value copyBackVar) {
952 cleanups.emplace_back(
953 CallCleanUp{CallCleanUp::CopyIn{tempBox, wasCopied, copyBackVar}});
954 }
955 void pushExprAssociateCleanUp(mlir::Value tempVar, mlir::Value wasCopied) {
956 cleanups.emplace_back(
957 CallCleanUp{CallCleanUp::ExprAssociate{tempVar, wasCopied}});
958 }
959 void pushExprAssociateCleanUp(hlfir::AssociateOp associate) {
960 mlir::Value hlfirBase = associate.getBase();
961 mlir::Value firBase = associate.getFirBase();
962 cleanups.emplace_back(CallCleanUp{CallCleanUp::ExprAssociate{
963 hlfir::mayHaveAllocatableComponent(hlfirBase.getType()) ? hlfirBase
964 : firBase,
965 associate.getMustFreeStrorageFlag()}});
966 }
967
968 mlir::Value dummy;
969 // NOTE: the clean-ups are executed in reverse order.
970 llvm::SmallVector<CallCleanUp, 2> cleanups;
971 };
972
973 /// Structure to help conditionally preparing a dummy argument based
974 /// on the actual argument presence.
975 /// It helps "wrapping" the dummy and the clean-up information in
976 /// an if (present) {...}:
977 ///
978 /// %conditionallyPrepared = fir.if (%present) {
979 /// fir.result %preparedDummy
980 /// } else {
981 /// fir.result %absent
982 /// }
983 ///
984 struct ConditionallyPreparedDummy {
985 /// Create ConditionallyPreparedDummy from a preparedDummy that must
986 /// be wrapped in a fir.if.
987 ConditionallyPreparedDummy(PreparedDummyArgument &preparedDummy) {
988 thenResultValues.push_back(preparedDummy.dummy);
989 for (const CallCleanUp &c : preparedDummy.cleanups) {
990 if (const auto *copyInCleanUp =
991 std::get_if<CallCleanUp::CopyIn>(&c.cleanUp)) {
992 thenResultValues.push_back(copyInCleanUp->wasCopied);
993 if (copyInCleanUp->copyBackVar)
994 thenResultValues.push_back(copyInCleanUp->copyBackVar);
995 } else {
996 const auto &exprAssociate =
997 std::get<CallCleanUp::ExprAssociate>(c.cleanUp);
998 thenResultValues.push_back(exprAssociate.tempVar);
999 thenResultValues.push_back(exprAssociate.mustFree);
1000 }
1001 }
1002 }
1003
1004 /// Get the result types of the wrapping fir.if that must be created.
1005 llvm::SmallVector<mlir::Type> getIfResulTypes() const {
1006 llvm::SmallVector<mlir::Type> types;
1007 for (mlir::Value res : thenResultValues)
1008 types.push_back(res.getType());
1009 return types;
1010 }
1011
1012 /// Generate the "fir.result %preparedDummy" in the then branch of the
1013 /// wrapping fir.if.
1014 void genThenResult(mlir::Location loc, fir::FirOpBuilder &builder) const {
1015 builder.create<fir::ResultOp>(loc, thenResultValues);
1016 }
1017
1018 /// Generate the "fir.result %absent" in the else branch of the
1019 /// wrapping fir.if.
1020 void genElseResult(mlir::Location loc, fir::FirOpBuilder &builder) const {
1021 llvm::SmallVector<mlir::Value> elseResultValues;
1022 mlir::Type i1Type = builder.getI1Type();
1023 for (mlir::Value res : thenResultValues) {
1024 mlir::Type type = res.getType();
1025 if (type == i1Type)
1026 elseResultValues.push_back(builder.createBool(loc, false));
1027 else
1028 elseResultValues.push_back(builder.genAbsentOp(loc, type));
1029 }
1030 builder.create<fir::ResultOp>(loc, elseResultValues);
1031 }
1032
1033 /// Once the fir.if has been created, get the resulting %conditionallyPrepared
1034 /// dummy argument.
1035 PreparedDummyArgument
1036 getPreparedDummy(fir::IfOp ifOp,
1037 const PreparedDummyArgument &unconditionalDummy) {
1038 PreparedDummyArgument preparedDummy;
1039 preparedDummy.dummy = ifOp.getResults()[0];
1040 for (const CallCleanUp &c : unconditionalDummy.cleanups) {
1041 if (const auto *copyInCleanUp =
1042 std::get_if<CallCleanUp::CopyIn>(&c.cleanUp)) {
1043 mlir::Value copyBackVar;
1044 if (copyInCleanUp->copyBackVar)
1045 copyBackVar = ifOp.getResults().back();
1046 // tempBox is an hlfir.copy_in argument created outside of the
1047 // fir.if region. It needs not to be threaded as a fir.if result.
1048 preparedDummy.pushCopyInCleanUp(copyInCleanUp->tempBox,
1049 ifOp.getResults()[1], copyBackVar);
1050 } else {
1051 preparedDummy.pushExprAssociateCleanUp(ifOp.getResults()[1],
1052 ifOp.getResults()[2]);
1053 }
1054 }
1055 return preparedDummy;
1056 }
1057
1058 llvm::SmallVector<mlir::Value> thenResultValues;
1059 };
1060 } // namespace
1061
1062 /// Fix-up the fact that it is supported to pass a character procedure
1063 /// designator to a non character procedure dummy procedure and vice-versa, even
1064 /// in case of explicit interface. Uglier cases where an object is passed as
1065 /// procedure designator or vice versa are handled only for implicit interfaces
1066 /// (refused by semantics with explicit interface), and handled with a funcOp
1067 /// cast like other implicit interface mismatches.
1068 static hlfir::Entity fixProcedureDummyMismatch(mlir::Location loc,
1069 fir::FirOpBuilder &builder,
1070 hlfir::Entity actual,
1071 mlir::Type dummyType) {
1072 if (mlir::isa<fir::BoxProcType>(actual.getType()) &&
1073 fir::isCharacterProcedureTuple(dummyType)) {
1074 mlir::Value length =
1075 builder.create<fir::UndefOp>(loc, builder.getCharacterLengthType());
1076 mlir::Value tuple = fir::factory::createCharacterProcedureTuple(
1077 builder, loc, dummyType, actual, length);
1078 return hlfir::Entity{tuple};
1079 }
1080 assert(fir::isCharacterProcedureTuple(actual.getType()) &&
1081 mlir::isa<fir::BoxProcType>(dummyType) &&
1082 "unsupported dummy procedure mismatch with the actual argument");
1083 mlir::Value boxProc = fir::factory::extractCharacterProcedureTuple(
1084 builder, loc, actual, /*openBoxProc=*/false)
1085 .first;
1086 return hlfir::Entity{boxProc};
1087 }
1088
1089 mlir::Value static getZeroLowerBounds(mlir::Location loc,
1090 fir::FirOpBuilder &builder,
1091 hlfir::Entity entity) {
1092 assert(!entity.isAssumedRank() &&
1093 "assumed-rank must use fir.rebox_assumed_rank");
1094 if (entity.getRank() < 1)
1095 return {};
1096 mlir::Value zero =
1097 builder.createIntegerConstant(loc, builder.getIndexType(), 0);
1098 llvm::SmallVector<mlir::Value> lowerBounds(entity.getRank(), zero);
1099 return builder.genShift(loc, lowerBounds);
1100 }
1101
1102 static bool
1103 isSimplyContiguous(const Fortran::evaluate::ActualArgument &arg,
1104 Fortran::evaluate::FoldingContext &foldingContext) {
1105 if (const auto *expr = arg.UnwrapExpr())
1106 return Fortran::evaluate::IsSimplyContiguous(*expr, foldingContext);
1107 const Fortran::semantics::Symbol *sym = arg.GetAssumedTypeDummy();
1108 assert(sym &&
1109 "expect ActualArguments to be expression or assumed-type symbols");
1110 return sym->Rank() == 0 ||
1111 Fortran::evaluate::IsSimplyContiguous(*sym, foldingContext);
1112 }
1113
1114 /// When dummy is not ALLOCATABLE, POINTER and is not passed in register,
1115 /// prepare the actual argument according to the interface. Do as needed:
1116 /// - address element if this is an array argument in an elemental call.
1117 /// - set dynamic type to the dummy type if the dummy is not polymorphic.
1118 /// - copy-in into contiguous variable if the dummy must be contiguous
1119 /// - copy into a temporary if the dummy has the VALUE attribute.
1120 /// - package the prepared dummy as required (fir.box, fir.class,
1121 /// fir.box_char...).
1122 /// This function should only be called with an actual that is present.
1123 /// The optional aspects must be handled by this function user.
1124 static PreparedDummyArgument preparePresentUserCallActualArgument(
1125 mlir::Location loc, fir::FirOpBuilder &builder,
1126 const Fortran::lower::PreparedActualArgument &preparedActual,
1127 mlir::Type dummyType,
1128 const Fortran::lower::CallerInterface::PassedEntity &arg,
1129 CallContext &callContext) {
1130
1131 Fortran::evaluate::FoldingContext &foldingContext =
1132 callContext.converter.getFoldingContext();
1133
1134 // Step 1: get the actual argument, which includes addressing the
1135 // element if this is an array in an elemental call.
1136 hlfir::Entity actual = preparedActual.getActual(loc, builder);
1137
1138 // Handle procedure arguments (procedure pointers should go through
1139 // prepareProcedurePointerActualArgument).
1140 if (hlfir::isFortranProcedureValue(dummyType)) {
1141 // Procedure pointer or function returns procedure pointer actual to
1142 // procedure dummy.
1143 if (actual.isProcedurePointer()) {
1144 actual = hlfir::derefPointersAndAllocatables(loc, builder, actual);
1145 return PreparedDummyArgument{actual, /*cleanups=*/{}};
1146 }
1147 // Procedure actual to procedure dummy.
1148 assert(actual.isProcedure());
1149 // Do nothing if this is a procedure argument. It is already a
1150 // fir.boxproc/fir.tuple<fir.boxproc, len> as it should.
1151 if (!mlir::isa<fir::BoxProcType>(actual.getType()) &&
1152 actual.getType() != dummyType)
1153 // The actual argument may be a procedure that returns character (a
1154 // fir.tuple<fir.boxproc, len>) while the dummy is not. Extract the tuple
1155 // in that case.
1156 actual = fixProcedureDummyMismatch(loc, builder, actual, dummyType);
1157 return PreparedDummyArgument{actual, /*cleanups=*/{}};
1158 }
1159
1160 const bool ignoreTKRtype = arg.testTKR(Fortran::common::IgnoreTKR::Type);
1161 const bool passingPolymorphicToNonPolymorphic =
1162 actual.isPolymorphic() && !fir::isPolymorphicType(dummyType) &&
1163 !ignoreTKRtype;
1164
1165 // When passing a CLASS(T) to TYPE(T), only the "T" part must be
1166 // passed. Unless the entity is a scalar passed by raw address, a
1167 // new descriptor must be made using the dummy argument type as
1168 // dynamic type. This must be done before any copy/copy-in because the
1169 // dynamic type matters to determine the contiguity.
1170 const bool mustSetDynamicTypeToDummyType =
1171 passingPolymorphicToNonPolymorphic &&
1172 (actual.isArray() || mlir::isa<fir::BaseBoxType>(dummyType));
1173
1174 // The simple contiguity of the actual is "lost" when passing a polymorphic
1175 // to a non polymorphic entity because the dummy dynamic type matters for
1176 // the contiguity.
1177 const bool mustDoCopyInOut =
1178 actual.isArray() && arg.mustBeMadeContiguous() &&
1179 (passingPolymorphicToNonPolymorphic ||
1180 !isSimplyContiguous(*arg.entity, foldingContext));
1181
1182 const bool actualIsAssumedRank = actual.isAssumedRank();
1183 // Create dummy type with actual argument rank when the dummy is an assumed
1184 // rank. That way, all the operation to create dummy descriptors are ranked if
1185 // the actual argument is ranked, which allows simple code generation.
1186 // Also do the same when the dummy is a sequence associated descriptor
1187 // because the actual shape/rank may mismatch with the dummy, and the dummy
1188 // may be an assumed-size array, so any descriptor manipulation should use the
1189 // actual argument shape information. A descriptor with the dummy shape
1190 // information will be created later when all actual arguments are ready.
1191 mlir::Type dummyTypeWithActualRank = dummyType;
1192 if (auto baseBoxDummy = mlir::dyn_cast<fir::BaseBoxType>(dummyType)) {
1193 if (baseBoxDummy.isAssumedRank() ||
1194 arg.testTKR(Fortran::common::IgnoreTKR::Rank) ||
1195 arg.isSequenceAssociatedDescriptor()) {
1196 mlir::Type actualTy =
1197 hlfir::getFortranElementOrSequenceType(actual.getType());
1198 dummyTypeWithActualRank = baseBoxDummy.getBoxTypeWithNewShape(actualTy);
1199 }
1200 }
1201 // Preserve the actual type in the argument preparation in case IgnoreTKR(t)
1202 // is set (descriptors must be created with the actual type in this case, and
1203 // copy-in/copy-out should be driven by the contiguity with regard to the
1204 // actual type).
1205 if (ignoreTKRtype)
1206 dummyTypeWithActualRank = fir::changeElementType(
1207 dummyTypeWithActualRank, actual.getFortranElementType(),
1208 actual.isPolymorphic());
1209
1210 PreparedDummyArgument preparedDummy;
1211
1212 // Helpers to generate hlfir.copy_in operation and register the related
1213 // hlfir.copy_out creation.
1214 auto genCopyIn = [&](hlfir::Entity var, bool doCopyOut) -> hlfir::Entity {
1215 auto baseBoxTy = mlir::dyn_cast<fir::BaseBoxType>(var.getType());
1216 assert(baseBoxTy && "expect non simply contiguous variables to be boxes");
1217 // Create allocatable descriptor for the potential temporary.
1218 mlir::Type tempBoxType = baseBoxTy.getBoxTypeWithNewAttr(
1219 fir::BaseBoxType::Attribute::Allocatable);
1220 mlir::Value tempBox = builder.createTemporary(loc, tempBoxType);
1221 auto copyIn = builder.create<hlfir::CopyInOp>(
1222 loc, var, tempBox, /*var_is_present=*/mlir::Value{});
1223 // Register the copy-out after the call.
1224 preparedDummy.pushCopyInCleanUp(copyIn.getTempBox(), copyIn.getWasCopied(),
1225 doCopyOut ? copyIn.getVar()
1226 : mlir::Value{});
1227 return hlfir::Entity{copyIn.getCopiedIn()};
1228 };
1229
1230 auto genSetDynamicTypeToDummyType = [&](hlfir::Entity var) -> hlfir::Entity {
1231 fir::BaseBoxType boxType = fir::BoxType::get(
1232 hlfir::getFortranElementOrSequenceType(dummyTypeWithActualRank));
1233 if (actualIsAssumedRank)
1234 return hlfir::Entity{builder.create<fir::ReboxAssumedRankOp>(
1235 loc, boxType, var, fir::LowerBoundModifierAttribute::SetToOnes)};
1236 // Use actual shape when creating descriptor with dummy type, the dummy
1237 // shape may be unknown in case of sequence association.
1238 mlir::Type actualTy =
1239 hlfir::getFortranElementOrSequenceType(actual.getType());
1240 boxType = boxType.getBoxTypeWithNewShape(actualTy);
1241 return hlfir::Entity{builder.create<fir::ReboxOp>(loc, boxType, var,
1242 /*shape=*/mlir::Value{},
1243 /*slice=*/mlir::Value{})};
1244 };
1245
1246 // Step 2: prepare the storage for the dummy arguments, ensuring that it
1247 // matches the dummy requirements (e.g., must be contiguous or must be
1248 // a temporary).
1249 hlfir::Entity entity =
1250 hlfir::derefPointersAndAllocatables(loc, builder, actual);
1251 if (entity.isVariable()) {
1252 // Set dynamic type if needed before any copy-in or copy so that the dummy
1253 // is contiguous according to the dummy type.
1254 if (mustSetDynamicTypeToDummyType)
1255 entity = genSetDynamicTypeToDummyType(entity);
1256 if (arg.hasValueAttribute() ||
1257 // Constant expressions might be lowered as variables with
1258 // 'parameter' attribute. Even though the constant expressions
1259 // are not definable and explicit assignments to them are not
1260 // possible, we have to create a temporary copies when we pass
1261 // them down the call stack.
1262 entity.isParameter()) {
1263 // Make a copy in a temporary.
1264 auto copy = builder.create<hlfir::AsExprOp>(loc, entity);
1265 mlir::Type storageType = entity.getType();
1266 mlir::NamedAttribute byRefAttr = fir::getAdaptToByRefAttr(builder);
1267 hlfir::AssociateOp associate = hlfir::genAssociateExpr(
1268 loc, builder, hlfir::Entity{copy}, storageType, "", byRefAttr);
1269 entity = hlfir::Entity{associate.getBase()};
1270 // Register the temporary destruction after the call.
1271 preparedDummy.pushExprAssociateCleanUp(associate);
1272 } else if (mustDoCopyInOut) {
1273 // Copy-in non contiguous variables.
1274 // TODO: for non-finalizable monomorphic derived type actual
1275 // arguments associated with INTENT(OUT) dummy arguments
1276 // we may avoid doing the copy and only allocate the temporary.
1277 // The codegen would do a "mold" allocation instead of "sourced"
1278 // allocation for the temp in this case. We can communicate
1279 // this to the codegen via some CopyInOp flag.
1280 // This is a performance concern.
1281 entity = genCopyIn(entity, arg.mayBeModifiedByCall());
1282 }
1283 } else {
1284 const Fortran::lower::SomeExpr *expr = arg.entity->UnwrapExpr();
1285 assert(expr && "expression actual argument cannot be an assumed type");
1286 // The actual is an expression value, place it into a temporary
1287 // and register the temporary destruction after the call.
1288 mlir::Type storageType = callContext.converter.genType(*expr);
1289 mlir::NamedAttribute byRefAttr = fir::getAdaptToByRefAttr(builder);
1290 hlfir::AssociateOp associate = hlfir::genAssociateExpr(
1291 loc, builder, entity, storageType, "", byRefAttr);
1292 entity = hlfir::Entity{associate.getBase()};
1293 preparedDummy.pushExprAssociateCleanUp(associate);
1294 // Rebox the actual argument to the dummy argument's type, and make sure
1295 // that we pass a contiguous entity (i.e. make copy-in, if needed).
1296 //
1297 // TODO: this can probably be optimized by associating the expression with
1298 // properly typed temporary, but this needs either a new operation or
1299 // making the hlfir.associate more complex.
1300 if (mustSetDynamicTypeToDummyType) {
1301 entity = genSetDynamicTypeToDummyType(entity);
1302 entity = genCopyIn(entity, /*doCopyOut=*/false);
1303 }
1304 }
1305
1306 // Step 3: now that the dummy argument storage has been prepared, package
1307 // it according to the interface.
1308 mlir::Value addr;
1309 if (mlir::isa<fir::BoxCharType>(dummyTypeWithActualRank)) {
1310 addr = hlfir::genVariableBoxChar(loc, builder, entity);
1311 } else if (mlir::isa<fir::BaseBoxType>(dummyTypeWithActualRank)) {
1312 entity = hlfir::genVariableBox(loc, builder, entity);
1313 // Ensures the box has the right attributes and that it holds an
1314 // addendum if needed.
1315 fir::BaseBoxType actualBoxType =
1316 mlir::cast<fir::BaseBoxType>(entity.getType());
1317 mlir::Type boxEleType = actualBoxType.getEleTy();
1318 // For now, assume it is not OK to pass the allocatable/pointer
1319 // descriptor to a non pointer/allocatable dummy. That is a strict
1320 // interpretation of 18.3.6 point 4 that stipulates the descriptor
1321 // has the dummy attributes in BIND(C) contexts.
1322 const bool actualBoxHasAllocatableOrPointerFlag =
1323 fir::isa_ref_type(boxEleType);
1324 // Fortran 2018 18.5.3, pp3: BIND(C) non pointer allocatable descriptors
1325 // must have zero lower bounds.
1326 bool needsZeroLowerBounds = callContext.isBindcCall() && entity.isArray();
1327 // On the callee side, the current code generated for unlimited
1328 // polymorphic might unconditionally read the addendum. Intrinsic type
1329 // descriptors may not have an addendum, the rebox below will create a
1330 // descriptor with an addendum in such case.
1331 const bool actualBoxHasAddendum = fir::boxHasAddendum(actualBoxType);
1332 const bool needToAddAddendum =
1333 fir::isUnlimitedPolymorphicType(dummyTypeWithActualRank) &&
1334 !actualBoxHasAddendum;
1335 if (needToAddAddendum || actualBoxHasAllocatableOrPointerFlag ||
1336 needsZeroLowerBounds) {
1337 if (actualIsAssumedRank) {
1338 auto lbModifier = needsZeroLowerBounds
1339 ? fir::LowerBoundModifierAttribute::SetToZeroes
1340 : fir::LowerBoundModifierAttribute::SetToOnes;
1341 entity = hlfir::Entity{builder.create<fir::ReboxAssumedRankOp>(
1342 loc, dummyTypeWithActualRank, entity, lbModifier)};
1343 } else {
1344 mlir::Value shift{};
1345 if (needsZeroLowerBounds)
1346 shift = getZeroLowerBounds(loc, builder, entity);
1347 entity = hlfir::Entity{builder.create<fir::ReboxOp>(
1348 loc, dummyTypeWithActualRank, entity, /*shape=*/shift,
1349 /*slice=*/mlir::Value{})};
1350 }
1351 }
1352 addr = entity;
1353 } else {
1354 addr = hlfir::genVariableRawAddress(loc, builder, entity);
1355 }
1356
1357 // For ranked actual passed to assumed-rank dummy, the cast to assumed-rank
1358 // box is inserted when building the fir.call op. Inserting it here would
1359 // cause the fir.if results to be assumed-rank in case of OPTIONAL dummy,
1360 // causing extra runtime costs due to the unknown runtime size of assumed-rank
1361 // descriptors.
1362 preparedDummy.dummy =
1363 builder.createConvert(loc, dummyTypeWithActualRank, addr);
1364 return preparedDummy;
1365 }
1366
1367 /// When dummy is not ALLOCATABLE, POINTER and is not passed in register,
1368 /// prepare the actual argument according to the interface, taking care
1369 /// of any optional aspect.
1370 static PreparedDummyArgument prepareUserCallActualArgument(
1371 mlir::Location loc, fir::FirOpBuilder &builder,
1372 const Fortran::lower::PreparedActualArgument &preparedActual,
1373 mlir::Type dummyType,
1374 const Fortran::lower::CallerInterface::PassedEntity &arg,
1375 CallContext &callContext) {
1376 if (!preparedActual.handleDynamicOptional())
1377 return preparePresentUserCallActualArgument(loc, builder, preparedActual,
1378 dummyType, arg, callContext);
1379
1380 // Conditional dummy argument preparation. The actual may be absent
1381 // at runtime, causing any addressing, copy, and packaging to have
1382 // undefined behavior.
1383 // To simplify the handling of this case, the "normal" dummy preparation
1384 // helper is used, except its generated code is wrapped inside a
1385 // fir.if(present).
1386 mlir::Value isPresent = preparedActual.getIsPresent();
1387 mlir::OpBuilder::InsertPoint insertPt = builder.saveInsertionPoint();
1388
1389 // Code generated in a preparation block that will become the
1390 // "then" block in "if (present) then {} else {}". The reason
1391 // for this unusual if/then/else generation is that the number
1392 // and types of the if results will depend on how the argument
1393 // is prepared, and forecasting that here would be brittle.
1394 auto badIfOp = builder.create<fir::IfOp>(loc, dummyType, isPresent,
1395 /*withElseRegion=*/false);
1396 mlir::Block *preparationBlock = &badIfOp.getThenRegion().front();
1397 builder.setInsertionPointToStart(preparationBlock);
1398 PreparedDummyArgument unconditionalDummy =
1399 preparePresentUserCallActualArgument(loc, builder, preparedActual,
1400 dummyType, arg, callContext);
1401 builder.restoreInsertionPoint(insertPt);
1402
1403 // TODO: when forwarding an optional to an optional of the same kind
1404 // (i.e, unconditionalDummy.dummy was not created in preparationBlock),
1405 // the if/then/else generation could be skipped to improve the generated
1406 // code.
1407
1408 // Now that the result types of the ifOp can be deduced, generate
1409 // the "real" ifOp (operation result types cannot be changed, so
1410 // badIfOp cannot be modified and used here).
1411 llvm::SmallVector<mlir::Type> ifOpResultTypes;
1412 ConditionallyPreparedDummy conditionalDummy(unconditionalDummy);
1413 auto ifOp = builder.create<fir::IfOp>(loc, conditionalDummy.getIfResulTypes(),
1414 isPresent,
1415 /*withElseRegion=*/true);
1416 // Move "preparationBlock" into the "then" of the new
1417 // fir.if operation and create fir.result propagating
1418 // unconditionalDummy.
1419 preparationBlock->moveBefore(&ifOp.getThenRegion().back());
1420 ifOp.getThenRegion().back().erase();
1421 builder.setInsertionPointToEnd(&ifOp.getThenRegion().front());
1422 conditionalDummy.genThenResult(loc, builder);
1423
1424 // Generate "else" branch with returning absent values.
1425 builder.setInsertionPointToStart(&ifOp.getElseRegion().front());
1426 conditionalDummy.genElseResult(loc, builder);
1427
1428 // Build dummy from IfOpResults.
1429 builder.setInsertionPointAfter(ifOp);
1430 PreparedDummyArgument result =
1431 conditionalDummy.getPreparedDummy(ifOp, unconditionalDummy);
1432 badIfOp->erase();
1433 return result;
1434 }
1435
1436 /// Prepare actual argument for a procedure pointer dummy.
1437 static PreparedDummyArgument prepareProcedurePointerActualArgument(
1438 mlir::Location loc, fir::FirOpBuilder &builder,
1439 const Fortran::lower::PreparedActualArgument &preparedActual,
1440 mlir::Type dummyType,
1441 const Fortran::lower::CallerInterface::PassedEntity &arg,
1442 CallContext &callContext) {
1443
1444 // NULL() actual to procedure pointer dummy
1445 if (Fortran::evaluate::UnwrapExpr<Fortran::evaluate::NullPointer>(
1446 *arg.entity) &&
1447 fir::isBoxProcAddressType(dummyType)) {
1448 auto boxTy{Fortran::lower::getUntypedBoxProcType(builder.getContext())};
1449 auto tempBoxProc{builder.createTemporary(loc, boxTy)};
1450 hlfir::Entity nullBoxProc(
1451 fir::factory::createNullBoxProc(builder, loc, boxTy));
1452 builder.create<fir::StoreOp>(loc, nullBoxProc, tempBoxProc);
1453 return PreparedDummyArgument{tempBoxProc, /*cleanups=*/{}};
1454 }
1455 hlfir::Entity actual = preparedActual.getActual(loc, builder);
1456 if (actual.isProcedurePointer())
1457 return PreparedDummyArgument{actual, /*cleanups=*/{}};
1458 assert(actual.isProcedure());
1459 // Procedure actual to procedure pointer dummy.
1460 auto tempBoxProc{builder.createTemporary(loc, actual.getType())};
1461 builder.create<fir::StoreOp>(loc, actual, tempBoxProc);
1462 return PreparedDummyArgument{tempBoxProc, /*cleanups=*/{}};
1463 }
1464
1465 /// Prepare arguments of calls to user procedures with actual arguments that
1466 /// have been pre-lowered but not yet prepared according to the interface.
1467 void prepareUserCallArguments(
1468 Fortran::lower::PreparedActualArguments &loweredActuals,
1469 Fortran::lower::CallerInterface &caller, mlir::FunctionType callSiteType,
1470 CallContext &callContext, llvm::SmallVector<CallCleanUp> &callCleanUps) {
1471 using PassBy = Fortran::lower::CallerInterface::PassEntityBy;
1472 mlir::Location loc = callContext.loc;
1473 bool mustRemapActualToDummyDescriptors = false;
1474 fir::FirOpBuilder &builder = callContext.getBuilder();
1475 for (auto [preparedActual, arg] :
1476 llvm::zip(loweredActuals, caller.getPassedArguments())) {
1477 mlir::Type argTy = callSiteType.getInput(arg.firArgument);
1478 if (!preparedActual) {
1479 // Optional dummy argument for which there is no actual argument.
1480 caller.placeInput(arg, builder.genAbsentOp(loc, argTy));
1481 continue;
1482 }
1483
1484 switch (arg.passBy) {
1485 case PassBy::Value: {
1486 // True pass-by-value semantics.
1487 assert(!preparedActual->handleDynamicOptional() && "cannot be optional");
1488 hlfir::Entity actual = preparedActual->getActual(loc, builder);
1489 hlfir::Entity value = hlfir::loadTrivialScalar(loc, builder, actual);
1490
1491 mlir::Type eleTy = value.getFortranElementType();
1492 if (fir::isa_builtin_cptr_type(eleTy)) {
1493 // Pass-by-value argument of type(C_PTR/C_FUNPTR).
1494 // Load the __address component and pass it by value.
1495 if (value.isValue()) {
1496 auto associate = hlfir::genAssociateExpr(loc, builder, value, eleTy,
1497 "adapt.cptrbyval");
1498 value = hlfir::Entity{genRecordCPtrValueArg(
1499 builder, loc, associate.getFirBase(), eleTy)};
1500 builder.create<hlfir::EndAssociateOp>(loc, associate);
1501 } else {
1502 value =
1503 hlfir::Entity{genRecordCPtrValueArg(builder, loc, value, eleTy)};
1504 }
1505 } else if (fir::isa_derived(value.getFortranElementType()) ||
1506 value.isCharacter()) {
1507 // BIND(C), VALUE derived type or character. The value must really
1508 // be loaded here.
1509 auto [exv, cleanup] = hlfir::convertToValue(loc, builder, value);
1510 mlir::Value loadedValue = fir::getBase(exv);
1511 // Character actual arguments may have unknown length or a length longer
1512 // than one. Cast the memory ref to the dummy type so that the load is
1513 // valid and only loads what is needed.
1514 if (mlir::Type baseTy = fir::dyn_cast_ptrEleTy(loadedValue.getType()))
1515 if (fir::isa_char(baseTy))
1516 loadedValue = builder.createConvert(
1517 loc, fir::ReferenceType::get(argTy), loadedValue);
1518 if (fir::isa_ref_type(loadedValue.getType()))
1519 loadedValue = builder.create<fir::LoadOp>(loc, loadedValue);
1520 caller.placeInput(arg, loadedValue);
1521 if (cleanup)
1522 (*cleanup)();
1523 break;
1524 }
1525 caller.placeInput(arg, builder.createConvert(loc, argTy, value));
1526 } break;
1527 case PassBy::BaseAddressValueAttribute:
1528 case PassBy::CharBoxValueAttribute:
1529 case PassBy::Box:
1530 case PassBy::BaseAddress:
1531 case PassBy::BoxChar: {
1532 PreparedDummyArgument preparedDummy = prepareUserCallActualArgument(
1533 loc, builder, *preparedActual, argTy, arg, callContext);
1534 callCleanUps.append(preparedDummy.cleanups.rbegin(),
1535 preparedDummy.cleanups.rend());
1536 caller.placeInput(arg, preparedDummy.dummy);
1537 if (arg.passBy == PassBy::Box)
1538 mustRemapActualToDummyDescriptors |=
1539 arg.isSequenceAssociatedDescriptor();
1540 } break;
1541 case PassBy::BoxProcRef: {
1542 PreparedDummyArgument preparedDummy =
1543 prepareProcedurePointerActualArgument(loc, builder, *preparedActual,
1544 argTy, arg, callContext);
1545 callCleanUps.append(preparedDummy.cleanups.rbegin(),
1546 preparedDummy.cleanups.rend());
1547 caller.placeInput(arg, preparedDummy.dummy);
1548 } break;
1549 case PassBy::AddressAndLength:
1550 // PassBy::AddressAndLength is only used for character results. Results
1551 // are not handled here.
1552 fir::emitFatalError(
1553 loc, "unexpected PassBy::AddressAndLength for actual arguments");
1554 break;
1555 case PassBy::CharProcTuple: {
1556 hlfir::Entity actual = preparedActual->getActual(loc, builder);
1557 if (actual.isProcedurePointer())
1558 actual = hlfir::derefPointersAndAllocatables(loc, builder, actual);
1559 if (!fir::isCharacterProcedureTuple(actual.getType()))
1560 actual = fixProcedureDummyMismatch(loc, builder, actual, argTy);
1561 caller.placeInput(arg, actual);
1562 } break;
1563 case PassBy::MutableBox: {
1564 const Fortran::lower::SomeExpr *expr = arg.entity->UnwrapExpr();
1565 // C709 and C710.
1566 assert(expr && "cannot pass TYPE(*) to POINTER or ALLOCATABLE");
1567 hlfir::Entity actual = preparedActual->getActual(loc, builder);
1568 if (Fortran::evaluate::UnwrapExpr<Fortran::evaluate::NullPointer>(
1569 *expr)) {
1570 // If expr is NULL(), the mutableBox created must be a deallocated
1571 // pointer with the dummy argument characteristics (see table 16.5
1572 // in Fortran 2018 standard).
1573 // No length parameters are set for the created box because any non
1574 // deferred type parameters of the dummy will be evaluated on the
1575 // callee side, and it is illegal to use NULL without a MOLD if any
1576 // dummy length parameters are assumed.
1577 mlir::Type boxTy = fir::dyn_cast_ptrEleTy(argTy);
1578 assert(boxTy && mlir::isa<fir::BaseBoxType>(boxTy) &&
1579 "must be a fir.box type");
1580 mlir::Value boxStorage =
1581 fir::factory::genNullBoxStorage(builder, loc, boxTy);
1582 caller.placeInput(arg, boxStorage);
1583 continue;
1584 }
1585 if (fir::isPointerType(argTy) &&
1586 !Fortran::evaluate::IsObjectPointer(*expr)) {
1587 // Passing a non POINTER actual argument to a POINTER dummy argument.
1588 // Create a pointer of the dummy argument type and assign the actual
1589 // argument to it.
1590 auto dataTy = llvm::cast<fir::BaseBoxType>(fir::unwrapRefType(argTy));
1591 fir::ExtendedValue actualExv = Fortran::lower::convertToAddress(
1592 loc, callContext.converter, actual, callContext.stmtCtx,
1593 hlfir::getFortranElementType(dataTy));
1594 // If the dummy is an assumed-rank pointer, allocate a pointer
1595 // descriptor with the actual argument rank (if it is not assumed-rank
1596 // itself).
1597 if (dataTy.isAssumedRank()) {
1598 dataTy =
1599 dataTy.getBoxTypeWithNewShape(fir::getBase(actualExv).getType());
1600 }
1601 mlir::Value irBox = builder.createTemporary(loc, dataTy);
1602 fir::MutableBoxValue ptrBox(irBox,
1603 /*nonDeferredParams=*/mlir::ValueRange{},
1604 /*mutableProperties=*/{});
1605 fir::factory::associateMutableBox(builder, loc, ptrBox, actualExv,
1606 /*lbounds=*/std::nullopt);
1607 caller.placeInput(arg, irBox);
1608 continue;
1609 }
1610 // Passing a POINTER to a POINTER, or an ALLOCATABLE to an ALLOCATABLE.
1611 assert(actual.isMutableBox() && "actual must be a mutable box");
1612 if (fir::isAllocatableType(argTy) && arg.isIntentOut() &&
1613 callContext.isBindcCall()) {
1614 // INTENT(OUT) allocatables are deallocated on the callee side,
1615 // but BIND(C) procedures may be implemented in C, so deallocation is
1616 // also done on the caller side (if the procedure is implemented in
1617 // Fortran, the deallocation attempt in the callee will be a no-op).
1618 auto [exv, cleanup] =
1619 hlfir::translateToExtendedValue(loc, builder, actual);
1620 const auto *mutableBox = exv.getBoxOf<fir::MutableBoxValue>();
1621 assert(mutableBox && !cleanup && "expect allocatable");
1622 Fortran::lower::genDeallocateIfAllocated(callContext.converter,
1623 *mutableBox, loc);
1624 }
1625 caller.placeInput(arg, actual);
1626 } break;
1627 }
1628 }
1629
1630 // Handle cases where caller must allocate the result or a fir.box for it.
1631 if (mustRemapActualToDummyDescriptors)
1632 remapActualToDummyDescriptors(loc, callContext.converter,
1633 callContext.symMap, loweredActuals, caller,
1634 callContext.isBindcCall());
1635 }
1636
1637 /// Lower calls to user procedures with actual arguments that have been
1638 /// pre-lowered but not yet prepared according to the interface.
1639 /// This can be called for elemental procedures, but only with scalar
1640 /// arguments: if there are array arguments, it must be provided with
1641 /// the array argument elements value and will return the corresponding
1642 /// scalar result value.
1643 static std::optional<hlfir::EntityWithAttributes>
1644 genUserCall(Fortran::lower::PreparedActualArguments &loweredActuals,
1645 Fortran::lower::CallerInterface &caller,
1646 mlir::FunctionType callSiteType, CallContext &callContext) {
1647 mlir::Location loc = callContext.loc;
1648 llvm::SmallVector<CallCleanUp> callCleanUps;
1649 fir::FirOpBuilder &builder = callContext.getBuilder();
1650
1651 prepareUserCallArguments(loweredActuals, caller, callSiteType, callContext,
1652 callCleanUps);
1653
1654 // Prepare lowered arguments according to the interface
1655 // and map the lowered values to the dummy
1656 // arguments.
1657 auto [result, resultIsFinalized] = Fortran::lower::genCallOpAndResult(
1658 loc, callContext.converter, callContext.symMap, callContext.stmtCtx,
1659 caller, callSiteType, callContext.resultType,
1660 callContext.isElementalProcWithArrayArgs());
1661 // For procedure pointer function result, just return the call.
1662 if (callContext.resultType &&
1663 mlir::isa<fir::BoxProcType>(*callContext.resultType))
1664 return hlfir::EntityWithAttributes(fir::getBase(result));
1665
1666 /// Clean-up associations and copy-in.
1667 for (auto cleanUp : callCleanUps)
1668 cleanUp.genCleanUp(loc, builder);
1669
1670 if (!fir::getBase(result))
1671 return std::nullopt; // subroutine call.
1672
1673 if (fir::isPointerType(fir::getBase(result).getType()))
1674 return extendedValueToHlfirEntity(loc, builder, result, tempResultName);
1675
1676 if (!resultIsFinalized) {
1677 hlfir::Entity resultEntity =
1678 extendedValueToHlfirEntity(loc, builder, result, tempResultName);
1679 resultEntity = loadTrivialScalar(loc, builder, resultEntity);
1680 if (resultEntity.isVariable()) {
1681 // If the result has no finalization, it can be moved into an expression.
1682 // In such case, the expression should not be freed after its use since
1683 // the result is stack allocated or deallocation (for allocatable results)
1684 // was already inserted in genCallOpAndResult.
1685 auto asExpr = builder.create<hlfir::AsExprOp>(
1686 loc, resultEntity, /*mustFree=*/builder.createBool(loc, false));
1687 return hlfir::EntityWithAttributes{asExpr.getResult()};
1688 }
1689 return hlfir::EntityWithAttributes{resultEntity};
1690 }
1691 // If the result has finalization, it cannot be moved because use of its
1692 // value have been created in the statement context and may be emitted
1693 // after the hlfir.expr destroy, so the result is kept as a variable in
1694 // HLFIR. This may lead to copies when passing the result to an argument
1695 // with VALUE, and this do not convey the fact that the result will not
1696 // change, but is correct, and using hlfir.expr without the move would
1697 // trigger a copy that may be avoided.
1698
1699 // Load allocatable results before emitting the hlfir.declare and drop its
1700 // lower bounds: this is not a variable From the Fortran point of view, so
1701 // the lower bounds are ones when inquired on the caller side.
1702 const auto *allocatable = result.getBoxOf<fir::MutableBoxValue>();
1703 fir::ExtendedValue loadedResult =
1704 allocatable
1705 ? fir::factory::genMutableBoxRead(builder, loc, *allocatable,
1706 /*mayBePolymorphic=*/true,
1707 /*preserveLowerBounds=*/false)
1708 : result;
1709 return extendedValueToHlfirEntity(loc, builder, loadedResult, tempResultName);
1710 }
1711
1712 /// Create an optional dummy argument value from an entity that may be
1713 /// absent. \p actualGetter callback returns hlfir::Entity denoting
1714 /// the lowered actual argument. \p actualGetter can only return numerical
1715 /// or logical scalar entity.
1716 /// If the entity is considered absent according to 15.5.2.12 point 1., the
1717 /// returned value is zero (or false), otherwise it is the value of the entity.
1718 /// \p eleType specifies the entity's Fortran element type.
1719 template <typename T>
1720 static ExvAndCleanup genOptionalValue(fir::FirOpBuilder &builder,
1721 mlir::Location loc, mlir::Type eleType,
1722 T actualGetter, mlir::Value isPresent) {
1723 return {builder
1724 .genIfOp(loc, {eleType}, isPresent,
1725 /*withElseRegion=*/true)
1726 .genThen([&]() {
1727 hlfir::Entity entity = actualGetter(loc, builder);
1728 assert(eleType == entity.getFortranElementType() &&
1729 "result type mismatch in genOptionalValue");
1730 assert(entity.isScalar() && fir::isa_trivial(eleType) &&
1731 "must be a numerical or logical scalar");
1732 mlir::Value val =
1733 hlfir::loadTrivialScalar(loc, builder, entity);
1734 builder.create<fir::ResultOp>(loc, val);
1735 })
1736 .genElse([&]() {
1737 mlir::Value zero =
1738 fir::factory::createZeroValue(builder, loc, eleType);
1739 builder.create<fir::ResultOp>(loc, zero);
1740 })
1741 .getResults()[0],
1742 std::nullopt};
1743 }
1744
1745 /// Create an optional dummy argument address from \p entity that may be
1746 /// absent. If \p entity is considered absent according to 15.5.2.12 point 1.,
1747 /// the returned value is a null pointer, otherwise it is the address of \p
1748 /// entity.
1749 static ExvAndCleanup genOptionalAddr(fir::FirOpBuilder &builder,
1750 mlir::Location loc, hlfir::Entity entity,
1751 mlir::Value isPresent) {
1752 auto [exv, cleanup] = hlfir::translateToExtendedValue(loc, builder, entity);
1753 // If it is an exv pointer/allocatable, then it cannot be absent
1754 // because it is passed to a non-pointer/non-allocatable.
1755 if (const auto *box = exv.getBoxOf<fir::MutableBoxValue>())
1756 return {fir::factory::genMutableBoxRead(builder, loc, *box), cleanup};
1757 // If this is not a POINTER or ALLOCATABLE, then it is already an OPTIONAL
1758 // address and can be passed directly.
1759 return {exv, cleanup};
1760 }
1761
1762 /// Create an optional dummy argument address from \p entity that may be
1763 /// absent. If \p entity is considered absent according to 15.5.2.12 point 1.,
1764 /// the returned value is an absent fir.box, otherwise it is a fir.box
1765 /// describing \p entity.
1766 static ExvAndCleanup genOptionalBox(fir::FirOpBuilder &builder,
1767 mlir::Location loc, hlfir::Entity entity,
1768 mlir::Value isPresent) {
1769 auto [exv, cleanup] = hlfir::translateToExtendedValue(loc, builder, entity);
1770
1771 // Non allocatable/pointer optional box -> simply forward
1772 if (exv.getBoxOf<fir::BoxValue>())
1773 return {exv, cleanup};
1774
1775 fir::ExtendedValue newExv = exv;
1776 // Optional allocatable/pointer -> Cannot be absent, but need to translate
1777 // unallocated/diassociated into absent fir.box.
1778 if (const auto *box = exv.getBoxOf<fir::MutableBoxValue>())
1779 newExv = fir::factory::genMutableBoxRead(builder, loc, *box);
1780
1781 // createBox will not do create any invalid memory dereferences if exv is
1782 // absent. The created fir.box will not be usable, but the SelectOp below
1783 // ensures it won't be.
1784 mlir::Value box = builder.createBox(loc, newExv);
1785 mlir::Type boxType = box.getType();
1786 auto absent = builder.create<fir::AbsentOp>(loc, boxType);
1787 auto boxOrAbsent = builder.create<mlir::arith::SelectOp>(
1788 loc, boxType, isPresent, box, absent);
1789 return {fir::BoxValue(boxOrAbsent), cleanup};
1790 }
1791
1792 /// Lower calls to intrinsic procedures with custom optional handling where the
1793 /// actual arguments have been pre-lowered
1794 static std::optional<hlfir::EntityWithAttributes> genCustomIntrinsicRefCore(
1795 Fortran::lower::PreparedActualArguments &loweredActuals,
1796 const Fortran::evaluate::SpecificIntrinsic *intrinsic,
1797 CallContext &callContext) {
1798 auto &builder = callContext.getBuilder();
1799 const auto &loc = callContext.loc;
1800 assert(intrinsic &&
1801 Fortran::lower::intrinsicRequiresCustomOptionalHandling(
1802 callContext.procRef, *intrinsic, callContext.converter));
1803
1804 // helper to get a particular prepared argument
1805 auto getArgument = [&](std::size_t i, bool loadArg) -> fir::ExtendedValue {
1806 if (!loweredActuals[i])
1807 return fir::getAbsentIntrinsicArgument();
1808 hlfir::Entity actual = loweredActuals[i]->getActual(loc, builder);
1809 if (loadArg && fir::conformsWithPassByRef(actual.getType())) {
1810 return hlfir::loadTrivialScalar(loc, builder, actual);
1811 }
1812 return Fortran::lower::translateToExtendedValue(loc, builder, actual,
1813 callContext.stmtCtx);
1814 };
1815 // helper to get the isPresent flag for a particular prepared argument
1816 auto isPresent = [&](std::size_t i) -> std::optional<mlir::Value> {
1817 if (!loweredActuals[i])
1818 return {builder.createBool(loc, false)};
1819 if (loweredActuals[i]->handleDynamicOptional())
1820 return {loweredActuals[i]->getIsPresent()};
1821 return std::nullopt;
1822 };
1823
1824 assert(callContext.resultType &&
1825 "the elemental intrinsics with custom handling are all functions");
1826 // if callContext.resultType is an array then this was originally an elemental
1827 // call. What we are lowering here is inside the kernel of the hlfir.elemental
1828 // so we should return the scalar type. If the return type is already a scalar
1829 // then it should be unchanged here.
1830 mlir::Type resTy = hlfir::getFortranElementType(*callContext.resultType);
1831 fir::ExtendedValue result = Fortran::lower::lowerCustomIntrinsic(
1832 builder, loc, callContext.getProcedureName(), resTy, isPresent,
1833 getArgument, loweredActuals.size(), callContext.stmtCtx);
1834
1835 return {hlfir::EntityWithAttributes{extendedValueToHlfirEntity(
1836 loc, builder, result, ".tmp.custom_intrinsic_result")}};
1837 }
1838
1839 /// Lower calls to intrinsic procedures with actual arguments that have been
1840 /// pre-lowered but have not yet been prepared according to the interface.
1841 static std::optional<hlfir::EntityWithAttributes>
1842 genIntrinsicRefCore(Fortran::lower::PreparedActualArguments &loweredActuals,
1843 const Fortran::evaluate::SpecificIntrinsic *intrinsic,
1844 const fir::IntrinsicHandlerEntry &intrinsicEntry,
1845 CallContext &callContext) {
1846 auto &converter = callContext.converter;
1847 if (intrinsic && Fortran::lower::intrinsicRequiresCustomOptionalHandling(
1848 callContext.procRef, *intrinsic, converter))
1849 return genCustomIntrinsicRefCore(loweredActuals, intrinsic, callContext);
1850 llvm::SmallVector<fir::ExtendedValue> operands;
1851 llvm::SmallVector<hlfir::CleanupFunction> cleanupFns;
1852 auto addToCleanups = [&cleanupFns](std::optional<hlfir::CleanupFunction> fn) {
1853 if (fn)
1854 cleanupFns.emplace_back(std::move(*fn));
1855 };
1856 auto &stmtCtx = callContext.stmtCtx;
1857 fir::FirOpBuilder &builder = callContext.getBuilder();
1858 mlir::Location loc = callContext.loc;
1859 const fir::IntrinsicArgumentLoweringRules *argLowering =
1860 intrinsicEntry.getArgumentLoweringRules();
1861 for (auto arg : llvm::enumerate(loweredActuals)) {
1862 if (!arg.value()) {
1863 operands.emplace_back(fir::getAbsentIntrinsicArgument());
1864 continue;
1865 }
1866 if (!argLowering) {
1867 // No argument lowering instruction, lower by value.
1868 assert(!arg.value()->handleDynamicOptional() &&
1869 "should use genOptionalValue");
1870 hlfir::Entity actual = arg.value()->getActual(loc, builder);
1871 operands.emplace_back(
1872 Fortran::lower::convertToValue(loc, converter, actual, stmtCtx));
1873 continue;
1874 }
1875 // Helper to get the type of the Fortran expression in case it is a
1876 // computed value that must be placed in memory (logicals are computed as
1877 // i1, but must be placed in memory as fir.logical).
1878 auto getActualFortranElementType = [&]() -> mlir::Type {
1879 if (const Fortran::lower::SomeExpr *expr =
1880 callContext.procRef.UnwrapArgExpr(arg.index())) {
1881
1882 mlir::Type type = converter.genType(*expr);
1883 return hlfir::getFortranElementType(type);
1884 }
1885 // TYPE(*): is already in memory anyway. Can return none
1886 // here.
1887 return builder.getNoneType();
1888 };
1889 // Ad-hoc argument lowering handling.
1890 fir::ArgLoweringRule argRules =
1891 fir::lowerIntrinsicArgumentAs(*argLowering, arg.index());
1892 if (arg.value()->handleDynamicOptional()) {
1893 mlir::Value isPresent = arg.value()->getIsPresent();
1894 switch (argRules.lowerAs) {
1895 case fir::LowerIntrinsicArgAs::Value: {
1896 // In case of elemental call, getActual() may produce
1897 // a designator denoting the array element to be passed
1898 // to the subprogram. If the actual array is dynamically
1899 // optional the designator must be generated under
1900 // isPresent check, because the box bounds reads will be
1901 // generated in the codegen. These reads are illegal,
1902 // if the dynamically optional argument is absent.
1903 auto getActualCb = [&](mlir::Location loc,
1904 fir::FirOpBuilder &builder) -> hlfir::Entity {
1905 return arg.value()->getActual(loc, builder);
1906 };
1907 auto [exv, cleanup] =
1908 genOptionalValue(builder, loc, getActualFortranElementType(),
1909 getActualCb, isPresent);
1910 addToCleanups(std::move(cleanup));
1911 operands.emplace_back(exv);
1912 continue;
1913 }
1914 case fir::LowerIntrinsicArgAs::Addr: {
1915 hlfir::Entity actual = arg.value()->getActual(loc, builder);
1916 auto [exv, cleanup] = genOptionalAddr(builder, loc, actual, isPresent);
1917 addToCleanups(std::move(cleanup));
1918 operands.emplace_back(exv);
1919 continue;
1920 }
1921 case fir::LowerIntrinsicArgAs::Box: {
1922 hlfir::Entity actual = arg.value()->getActual(loc, builder);
1923 auto [exv, cleanup] = genOptionalBox(builder, loc, actual, isPresent);
1924 addToCleanups(std::move(cleanup));
1925 operands.emplace_back(exv);
1926 continue;
1927 }
1928 case fir::LowerIntrinsicArgAs::Inquired: {
1929 hlfir::Entity actual = arg.value()->getActual(loc, builder);
1930 auto [exv, cleanup] =
1931 hlfir::translateToExtendedValue(loc, builder, actual);
1932 addToCleanups(std::move(cleanup));
1933 operands.emplace_back(exv);
1934 continue;
1935 }
1936 }
1937 llvm_unreachable("bad switch");
1938 }
1939
1940 hlfir::Entity actual = arg.value()->getActual(loc, builder);
1941 switch (argRules.lowerAs) {
1942 case fir::LowerIntrinsicArgAs::Value:
1943 operands.emplace_back(
1944 Fortran::lower::convertToValue(loc, converter, actual, stmtCtx));
1945 continue;
1946 case fir::LowerIntrinsicArgAs::Addr:
1947 operands.emplace_back(Fortran::lower::convertToAddress(
1948 loc, converter, actual, stmtCtx, getActualFortranElementType()));
1949 continue;
1950 case fir::LowerIntrinsicArgAs::Box:
1951 operands.emplace_back(Fortran::lower::convertToBox(
1952 loc, converter, actual, stmtCtx, getActualFortranElementType()));
1953 continue;
1954 case fir::LowerIntrinsicArgAs::Inquired:
1955 if (const Fortran::lower::SomeExpr *expr =
1956 callContext.procRef.UnwrapArgExpr(arg.index())) {
1957 if (Fortran::evaluate::UnwrapExpr<Fortran::evaluate::NullPointer>(
1958 *expr)) {
1959 // NULL() pointer without a MOLD must be passed as a deallocated
1960 // pointer (see table 16.5 in Fortran 2018 standard).
1961 // !fir.box<!fir.ptr<none>> should always be valid in this context.
1962 mlir::Type noneTy = mlir::NoneType::get(builder.getContext());
1963 mlir::Type nullPtrTy = fir::PointerType::get(noneTy);
1964 mlir::Type boxTy = fir::BoxType::get(nullPtrTy);
1965 mlir::Value boxStorage =
1966 fir::factory::genNullBoxStorage(builder, loc, boxTy);
1967 hlfir::EntityWithAttributes nullBoxEntity =
1968 extendedValueToHlfirEntity(loc, builder, boxStorage,
1969 ".tmp.null_box");
1970 operands.emplace_back(Fortran::lower::translateToExtendedValue(
1971 loc, builder, nullBoxEntity, stmtCtx));
1972 continue;
1973 }
1974 }
1975 // Place hlfir.expr in memory, and unbox fir.boxchar. Other entities
1976 // are translated to fir::ExtendedValue without transformation (notably,
1977 // pointers/allocatable are not dereferenced).
1978 // TODO: once lowering to FIR retires, UBOUND and LBOUND can be simplified
1979 // since the fir.box lowered here are now guaranteed to contain the local
1980 // lower bounds thanks to the hlfir.declare (the extra rebox can be
1981 // removed).
1982 operands.emplace_back(Fortran::lower::translateToExtendedValue(
1983 loc, builder, actual, stmtCtx));
1984 continue;
1985 }
1986 llvm_unreachable("bad switch");
1987 }
1988 // genIntrinsicCall needs the scalar type, even if this is a transformational
1989 // procedure returning an array.
1990 std::optional<mlir::Type> scalarResultType;
1991 if (callContext.resultType)
1992 scalarResultType = hlfir::getFortranElementType(*callContext.resultType);
1993 const std::string intrinsicName = callContext.getProcedureName();
1994 // Let the intrinsic library lower the intrinsic procedure call.
1995 auto [resultExv, mustBeFreed] = genIntrinsicCall(
1996 builder, loc, intrinsicEntry, scalarResultType, operands, &converter);
1997 for (const hlfir::CleanupFunction &fn : cleanupFns)
1998 fn();
1999 if (!fir::getBase(resultExv))
2000 return std::nullopt;
2001 hlfir::EntityWithAttributes resultEntity = extendedValueToHlfirEntity(
2002 loc, builder, resultExv, ".tmp.intrinsic_result");
2003 // Move result into memory into an hlfir.expr since they are immutable from
2004 // that point, and the result storage is some temp. "Null" is special: it
2005 // returns a null pointer variable that should not be transformed into a value
2006 // (what matters is the memory address).
2007 if (resultEntity.isVariable() && intrinsicName != "null") {
2008 assert(!fir::isa_trivial(fir::unwrapRefType(resultEntity.getType())) &&
2009 "expect intrinsic scalar results to not be in memory");
2010 hlfir::AsExprOp asExpr;
2011 // Character/Derived MERGE lowering returns one of its argument address
2012 // (this is the only intrinsic implemented in that way so far). The
2013 // ownership of this address cannot be taken here since it may not be a
2014 // temp.
2015 if (intrinsicName == "merge")
2016 asExpr = builder.create<hlfir::AsExprOp>(loc, resultEntity);
2017 else
2018 asExpr = builder.create<hlfir::AsExprOp>(
2019 loc, resultEntity, builder.createBool(loc, mustBeFreed));
2020 resultEntity = hlfir::EntityWithAttributes{asExpr.getResult()};
2021 }
2022 return resultEntity;
2023 }
2024
2025 /// Lower calls to intrinsic procedures with actual arguments that have been
2026 /// pre-lowered but have not yet been prepared according to the interface.
2027 static std::optional<hlfir::EntityWithAttributes> genHLFIRIntrinsicRefCore(
2028 Fortran::lower::PreparedActualArguments &loweredActuals,
2029 const Fortran::evaluate::SpecificIntrinsic *intrinsic,
2030 const fir::IntrinsicHandlerEntry &intrinsicEntry,
2031 CallContext &callContext) {
2032 // Try lowering transformational intrinsic ops to HLFIR ops if enabled
2033 // (transformational always have a result type)
2034 if (useHlfirIntrinsicOps && callContext.resultType) {
2035 fir::FirOpBuilder &builder = callContext.getBuilder();
2036 mlir::Location loc = callContext.loc;
2037 const std::string intrinsicName = callContext.getProcedureName();
2038 const fir::IntrinsicArgumentLoweringRules *argLowering =
2039 intrinsicEntry.getArgumentLoweringRules();
2040 std::optional<hlfir::EntityWithAttributes> res =
2041 Fortran::lower::lowerHlfirIntrinsic(builder, loc, intrinsicName,
2042 loweredActuals, argLowering,
2043 *callContext.resultType);
2044 if (res)
2045 return res;
2046 }
2047
2048 // fallback to calling the intrinsic via fir.call
2049 return genIntrinsicRefCore(loweredActuals, intrinsic, intrinsicEntry,
2050 callContext);
2051 }
2052
2053 namespace {
2054 template <typename ElementalCallBuilderImpl>
2055 class ElementalCallBuilder {
2056 public:
2057 std::optional<hlfir::EntityWithAttributes>
2058 genElementalCall(Fortran::lower::PreparedActualArguments &loweredActuals,
2059 bool isImpure, CallContext &callContext) {
2060 mlir::Location loc = callContext.loc;
2061 fir::FirOpBuilder &builder = callContext.getBuilder();
2062 unsigned numArgs = loweredActuals.size();
2063 // Step 1: dereference pointers/allocatables and compute elemental shape.
2064 mlir::Value shape;
2065 Fortran::lower::PreparedActualArgument *optionalWithShape;
2066 // 10.1.4 p5. Impure elemental procedures must be called in element order.
2067 bool mustBeOrdered = isImpure;
2068 for (unsigned i = 0; i < numArgs; ++i) {
2069 auto &preparedActual = loweredActuals[i];
2070 if (preparedActual) {
2071 // Elemental procedure dummy arguments cannot be pointer/allocatables
2072 // (C15100), so it is safe to dereference any pointer or allocatable
2073 // actual argument now instead of doing this inside the elemental
2074 // region.
2075 preparedActual->derefPointersAndAllocatables(loc, builder);
2076 // Better to load scalars outside of the loop when possible.
2077 if (!preparedActual->handleDynamicOptional() &&
2078 impl().canLoadActualArgumentBeforeLoop(i))
2079 preparedActual->loadTrivialScalar(loc, builder);
2080 // TODO: merge shape instead of using the first one.
2081 if (!shape && preparedActual->isArray()) {
2082 if (preparedActual->handleDynamicOptional())
2083 optionalWithShape = &*preparedActual;
2084 else
2085 shape = preparedActual->genShape(loc, builder);
2086 }
2087 // 15.8.3 p1. Elemental procedure with intent(out)/intent(inout)
2088 // arguments must be called in element order.
2089 if (impl().argMayBeModifiedByCall(i))
2090 mustBeOrdered = true;
2091 }
2092 }
2093 if (!shape && optionalWithShape) {
2094 // If all array operands appear in optional positions, then none of them
2095 // is allowed to be absent as per 15.5.2.12 point 3. (6). Just pick the
2096 // first operand.
2097 shape = optionalWithShape->genShape(loc, builder);
2098 // TODO: There is an opportunity to add a runtime check here that
2099 // this array is present as required. Also, the optionality of all actual
2100 // could be checked and reset given the Fortran requirement.
2101 optionalWithShape->resetOptionalAspect();
2102 }
2103 assert(shape &&
2104 "elemental array calls must have at least one array arguments");
2105
2106 // Evaluate the actual argument array expressions before the elemental
2107 // call of an impure subprogram or a subprogram with intent(out) or
2108 // intent(inout) arguments. Note that the scalar arguments are handled
2109 // above.
2110 if (mustBeOrdered) {
2111 for (auto &preparedActual : loweredActuals) {
2112 if (preparedActual) {
2113 if (hlfir::AssociateOp associate =
2114 preparedActual->associateIfArrayExpr(loc, builder)) {
2115 fir::FirOpBuilder *bldr = &builder;
2116 callContext.stmtCtx.attachCleanup(
2117 [=]() { bldr->create<hlfir::EndAssociateOp>(loc, associate); });
2118 }
2119 }
2120 }
2121 }
2122
2123 // Push a new local scope so that any temps made inside the elemental
2124 // iterations are cleaned up inside the iterations.
2125 if (!callContext.resultType) {
2126 // Subroutine case. Generate call inside loop nest.
2127 hlfir::LoopNest loopNest =
2128 hlfir::genLoopNest(loc, builder, shape, !mustBeOrdered);
2129 mlir::ValueRange oneBasedIndices = loopNest.oneBasedIndices;
2130 auto insPt = builder.saveInsertionPoint();
2131 builder.setInsertionPointToStart(loopNest.innerLoop.getBody());
2132 callContext.stmtCtx.pushScope();
2133 for (auto &preparedActual : loweredActuals)
2134 if (preparedActual)
2135 preparedActual->setElementalIndices(oneBasedIndices);
2136 impl().genElementalKernel(loweredActuals, callContext);
2137 callContext.stmtCtx.finalizeAndPop();
2138 builder.restoreInsertionPoint(insPt);
2139 return std::nullopt;
2140 }
2141 // Function case: generate call inside hlfir.elemental
2142 mlir::Type elementType =
2143 hlfir::getFortranElementType(*callContext.resultType);
2144 // Get result length parameters.
2145 llvm::SmallVector<mlir::Value> typeParams;
2146 if (mlir::isa<fir::CharacterType>(elementType) ||
2147 fir::isRecordWithTypeParameters(elementType)) {
2148 auto charType = mlir::dyn_cast<fir::CharacterType>(elementType);
2149 if (charType && charType.hasConstantLen())
2150 typeParams.push_back(builder.createIntegerConstant(
2151 loc, builder.getIndexType(), charType.getLen()));
2152 else if (charType)
2153 typeParams.push_back(impl().computeDynamicCharacterResultLength(
2154 loweredActuals, callContext));
2155 else
2156 TODO(
2157 loc,
2158 "compute elemental PDT function result length parameters in HLFIR");
2159 }
2160 auto genKernel = [&](mlir::Location l, fir::FirOpBuilder &b,
2161 mlir::ValueRange oneBasedIndices) -> hlfir::Entity {
2162 callContext.stmtCtx.pushScope();
2163 for (auto &preparedActual : loweredActuals)
2164 if (preparedActual)
2165 preparedActual->setElementalIndices(oneBasedIndices);
2166 auto res = *impl().genElementalKernel(loweredActuals, callContext);
2167 callContext.stmtCtx.finalizeAndPop();
2168 // Note that an hlfir.destroy is not emitted for the result since it
2169 // is still used by the hlfir.yield_element that also marks its last
2170 // use.
2171 return res;
2172 };
2173 mlir::Value polymorphicMold;
2174 if (fir::isPolymorphicType(*callContext.resultType))
2175 polymorphicMold =
2176 impl().getPolymorphicResultMold(loweredActuals, callContext);
2177 mlir::Value elemental =
2178 hlfir::genElementalOp(loc, builder, elementType, shape, typeParams,
2179 genKernel, !mustBeOrdered, polymorphicMold);
2180 // If the function result requires finalization, then it has to be done
2181 // for the array result of the elemental call. We have to communicate
2182 // this via the DestroyOp's attribute.
2183 bool mustFinalizeExpr = impl().resultMayRequireFinalization(callContext);
2184 fir::FirOpBuilder *bldr = &builder;
2185 callContext.stmtCtx.attachCleanup([=]() {
2186 bldr->create<hlfir::DestroyOp>(loc, elemental, mustFinalizeExpr);
2187 });
2188 return hlfir::EntityWithAttributes{elemental};
2189 }
2190
2191 private:
2192 ElementalCallBuilderImpl &impl() {
2193 return *static_cast<ElementalCallBuilderImpl *>(this);
2194 }
2195 };
2196
2197 class ElementalUserCallBuilder
2198 : public ElementalCallBuilder<ElementalUserCallBuilder> {
2199 public:
2200 ElementalUserCallBuilder(Fortran::lower::CallerInterface &caller,
2201 mlir::FunctionType callSiteType)
2202 : caller{caller}, callSiteType{callSiteType} {}
2203 std::optional<hlfir::Entity>
2204 genElementalKernel(Fortran::lower::PreparedActualArguments &loweredActuals,
2205 CallContext &callContext) {
2206 return genUserCall(loweredActuals, caller, callSiteType, callContext);
2207 }
2208
2209 bool argMayBeModifiedByCall(unsigned argIdx) const {
2210 assert(argIdx < caller.getPassedArguments().size() && "bad argument index");
2211 return caller.getPassedArguments()[argIdx].mayBeModifiedByCall();
2212 }
2213
2214 bool canLoadActualArgumentBeforeLoop(unsigned argIdx) const {
2215 using PassBy = Fortran::lower::CallerInterface::PassEntityBy;
2216 const auto &passedArgs{caller.getPassedArguments()};
2217 assert(argIdx < passedArgs.size() && "bad argument index");
2218 // If the actual argument does not need to be passed via an address,
2219 // or will be passed in the address of a temporary copy, it can be loaded
2220 // before the elemental loop nest.
2221 const auto &arg{passedArgs[argIdx]};
2222 return arg.passBy == PassBy::Value ||
2223 arg.passBy == PassBy::BaseAddressValueAttribute;
2224 }
2225
2226 mlir::Value computeDynamicCharacterResultLength(
2227 Fortran::lower::PreparedActualArguments &loweredActuals,
2228 CallContext &callContext) {
2229 fir::FirOpBuilder &builder = callContext.getBuilder();
2230 mlir::Location loc = callContext.loc;
2231 auto &converter = callContext.converter;
2232 mlir::Type idxTy = builder.getIndexType();
2233 llvm::SmallVector<CallCleanUp> callCleanUps;
2234
2235 prepareUserCallArguments(loweredActuals, caller, callSiteType, callContext,
2236 callCleanUps);
2237
2238 callContext.symMap.pushScope();
2239
2240 // Map prepared argument to dummy symbol to be able to lower spec expr.
2241 for (const auto &arg : caller.getPassedArguments()) {
2242 const Fortran::semantics::Symbol *sym = caller.getDummySymbol(arg);
2243 assert(sym && "expect symbol for dummy argument");
2244 auto input = caller.getInput(arg);
2245 fir::ExtendedValue exv = Fortran::lower::translateToExtendedValue(
2246 loc, builder, hlfir::Entity{input}, callContext.stmtCtx);
2247 fir::FortranVariableOpInterface variableIface = hlfir::genDeclare(
2248 loc, builder, exv, "dummy.tmp", fir::FortranVariableFlagsAttr{});
2249 callContext.symMap.addVariableDefinition(*sym, variableIface);
2250 }
2251
2252 auto lowerSpecExpr = [&](const auto &expr) -> mlir::Value {
2253 mlir::Value convertExpr = builder.createConvert(
2254 loc, idxTy,
2255 fir::getBase(converter.genExprValue(expr, callContext.stmtCtx)));
2256 return fir::factory::genMaxWithZero(builder, loc, convertExpr);
2257 };
2258
2259 llvm::SmallVector<mlir::Value> lengths;
2260 caller.walkResultLengths(
2261 [&](const Fortran::lower::SomeExpr &e, bool isAssumedSizeExtent) {
2262 assert(!isAssumedSizeExtent && "result cannot be assumed-size");
2263 lengths.emplace_back(lowerSpecExpr(e));
2264 });
2265 callContext.symMap.popScope();
2266 assert(lengths.size() == 1 && "expect 1 length parameter for the result");
2267 return lengths[0];
2268 }
2269
2270 mlir::Value getPolymorphicResultMold(
2271 Fortran::lower::PreparedActualArguments &loweredActuals,
2272 CallContext &callContext) {
2273 fir::emitFatalError(callContext.loc,
2274 "elemental function call with polymorphic result");
2275 return {};
2276 }
2277
2278 bool resultMayRequireFinalization(CallContext &callContext) const {
2279 std::optional<Fortran::evaluate::DynamicType> retTy =
2280 caller.getCallDescription().proc().GetType();
2281 if (!retTy)
2282 return false;
2283
2284 if (retTy->IsPolymorphic() || retTy->IsUnlimitedPolymorphic())
2285 fir::emitFatalError(
2286 callContext.loc,
2287 "elemental function call with [unlimited-]polymorphic result");
2288
2289 if (retTy->category() == Fortran::common::TypeCategory::Derived) {
2290 const Fortran::semantics::DerivedTypeSpec &typeSpec =
2291 retTy->GetDerivedTypeSpec();
2292 return Fortran::semantics::IsFinalizable(typeSpec);
2293 }
2294
2295 return false;
2296 }
2297
2298 private:
2299 Fortran::lower::CallerInterface &caller;
2300 mlir::FunctionType callSiteType;
2301 };
2302
2303 class ElementalIntrinsicCallBuilder
2304 : public ElementalCallBuilder<ElementalIntrinsicCallBuilder> {
2305 public:
2306 ElementalIntrinsicCallBuilder(
2307 const Fortran::evaluate::SpecificIntrinsic *intrinsic,
2308 const fir::IntrinsicHandlerEntry &intrinsicEntry, bool isFunction)
2309 : intrinsic{intrinsic}, intrinsicEntry{intrinsicEntry},
2310 isFunction{isFunction} {}
2311 std::optional<hlfir::Entity>
2312 genElementalKernel(Fortran::lower::PreparedActualArguments &loweredActuals,
2313 CallContext &callContext) {
2314 return genHLFIRIntrinsicRefCore(loweredActuals, intrinsic, intrinsicEntry,
2315 callContext);
2316 }
2317 // Elemental intrinsic functions cannot modify their arguments.
2318 bool argMayBeModifiedByCall(int) const { return !isFunction; }
2319 bool canLoadActualArgumentBeforeLoop(int) const {
2320 // Elemental intrinsic functions never need the actual addresses
2321 // of their arguments.
2322 return isFunction;
2323 }
2324
2325 mlir::Value computeDynamicCharacterResultLength(
2326 Fortran::lower::PreparedActualArguments &loweredActuals,
2327 CallContext &callContext) {
2328 if (intrinsic)
2329 if (intrinsic->name == "adjustr" || intrinsic->name == "adjustl" ||
2330 intrinsic->name == "merge")
2331 return loweredActuals[0].value().genCharLength(
2332 callContext.loc, callContext.getBuilder());
2333 // Character MIN/MAX is the min/max of the arguments length that are
2334 // present.
2335 TODO(callContext.loc,
2336 "compute elemental character min/max function result length in HLFIR");
2337 }
2338
2339 mlir::Value getPolymorphicResultMold(
2340 Fortran::lower::PreparedActualArguments &loweredActuals,
2341 CallContext &callContext) {
2342 if (!intrinsic)
2343 return {};
2344
2345 if (intrinsic->name == "merge") {
2346 // MERGE seems to be the only elemental function that can produce
2347 // polymorphic result. The MERGE's result is polymorphic iff
2348 // both TSOURCE and FSOURCE are polymorphic, and they also must have
2349 // the same declared and dynamic types. So any of them can be used
2350 // for the mold.
2351 assert(!loweredActuals.empty());
2352 return loweredActuals.front()->getPolymorphicMold(callContext.loc);
2353 }
2354
2355 return {};
2356 }
2357
2358 bool resultMayRequireFinalization(
2359 [[maybe_unused]] CallContext &callContext) const {
2360 // FIXME: need access to the CallerInterface's return type
2361 // to check if the result may need finalization (e.g. the result
2362 // of MERGE).
2363 return false;
2364 }
2365
2366 private:
2367 const Fortran::evaluate::SpecificIntrinsic *intrinsic;
2368 fir::IntrinsicHandlerEntry intrinsicEntry;
2369 const bool isFunction;
2370 };
2371 } // namespace
2372
2373 static std::optional<mlir::Value>
2374 genIsPresentIfArgMaybeAbsent(mlir::Location loc, hlfir::Entity actual,
2375 const Fortran::lower::SomeExpr &expr,
2376 CallContext &callContext,
2377 bool passAsAllocatableOrPointer) {
2378 if (!Fortran::evaluate::MayBePassedAsAbsentOptional(expr))
2379 return std::nullopt;
2380 fir::FirOpBuilder &builder = callContext.getBuilder();
2381 if (!passAsAllocatableOrPointer &&
2382 Fortran::evaluate::IsAllocatableOrPointerObject(expr)) {
2383 // Passing Allocatable/Pointer to non-pointer/non-allocatable OPTIONAL.
2384 // Fortran 2018 15.5.2.12 point 1: If unallocated/disassociated, it is
2385 // as if the argument was absent. The main care here is to not do a
2386 // copy-in/copy-out because the temp address, even though pointing to a
2387 // null size storage, would not be a nullptr and therefore the argument
2388 // would not be considered absent on the callee side. Note: if the
2389 // allocatable/pointer is also optional, it cannot be absent as per
2390 // 15.5.2.12 point 7. and 8. We rely on this to un-conditionally read
2391 // the allocatable/pointer descriptor here.
2392 mlir::Value addr = genVariableRawAddress(loc, builder, actual);
2393 return builder.genIsNotNullAddr(loc, addr);
2394 }
2395 // TODO: what if passing allocatable target to optional intent(in) pointer?
2396 // May fall into the category above if the allocatable is not optional.
2397
2398 // Passing an optional to an optional.
2399 return builder.create<fir::IsPresentOp>(loc, builder.getI1Type(), actual)
2400 .getResult();
2401 }
2402
2403 // Lower a reference to an elemental intrinsic procedure with array arguments
2404 // and custom optional handling
2405 static std::optional<hlfir::EntityWithAttributes>
2406 genCustomElementalIntrinsicRef(
2407 const Fortran::evaluate::SpecificIntrinsic *intrinsic,
2408 CallContext &callContext) {
2409 assert(callContext.isElementalProcWithArrayArgs() &&
2410 "Use genCustomIntrinsicRef for scalar calls");
2411 mlir::Location loc = callContext.loc;
2412 auto &converter = callContext.converter;
2413 Fortran::lower::PreparedActualArguments operands;
2414 assert(intrinsic && Fortran::lower::intrinsicRequiresCustomOptionalHandling(
2415 callContext.procRef, *intrinsic, converter));
2416
2417 // callback for optional arguments
2418 auto prepareOptionalArg = [&](const Fortran::lower::SomeExpr &expr) {
2419 hlfir::EntityWithAttributes actual = Fortran::lower::convertExprToHLFIR(
2420 loc, converter, expr, callContext.symMap, callContext.stmtCtx);
2421 std::optional<mlir::Value> isPresent =
2422 genIsPresentIfArgMaybeAbsent(loc, actual, expr, callContext,
2423 /*passAsAllocatableOrPointer=*/false);
2424 operands.emplace_back(
2425 Fortran::lower::PreparedActualArgument{actual, isPresent});
2426 };
2427
2428 // callback for non-optional arguments
2429 auto prepareOtherArg = [&](const Fortran::lower::SomeExpr &expr,
2430 fir::LowerIntrinsicArgAs lowerAs) {
2431 hlfir::EntityWithAttributes actual = Fortran::lower::convertExprToHLFIR(
2432 loc, converter, expr, callContext.symMap, callContext.stmtCtx);
2433 operands.emplace_back(Fortran::lower::PreparedActualArgument{
2434 actual, /*isPresent=*/std::nullopt});
2435 };
2436
2437 Fortran::lower::prepareCustomIntrinsicArgument(
2438 callContext.procRef, *intrinsic, callContext.resultType,
2439 prepareOptionalArg, prepareOtherArg, converter);
2440
2441 std::optional<fir::IntrinsicHandlerEntry> intrinsicEntry =
2442 fir::lookupIntrinsicHandler(callContext.getBuilder(),
2443 callContext.getProcedureName(),
2444 callContext.resultType);
2445 assert(intrinsicEntry.has_value() &&
2446 "intrinsic with custom handling for OPTIONAL arguments must have "
2447 "lowering entries");
2448 // All of the custom intrinsic elementals with custom handling are pure
2449 // functions
2450 return ElementalIntrinsicCallBuilder{intrinsic, *intrinsicEntry,
2451 /*isFunction=*/true}
2452 .genElementalCall(operands, /*isImpure=*/false, callContext);
2453 }
2454
2455 // Lower a reference to an intrinsic procedure with custom optional handling
2456 static std::optional<hlfir::EntityWithAttributes>
2457 genCustomIntrinsicRef(const Fortran::evaluate::SpecificIntrinsic *intrinsic,
2458 CallContext &callContext) {
2459 assert(!callContext.isElementalProcWithArrayArgs() &&
2460 "Needs to be run through ElementalIntrinsicCallBuilder first");
2461 mlir::Location loc = callContext.loc;
2462 fir::FirOpBuilder &builder = callContext.getBuilder();
2463 auto &converter = callContext.converter;
2464 auto &stmtCtx = callContext.stmtCtx;
2465 assert(intrinsic && Fortran::lower::intrinsicRequiresCustomOptionalHandling(
2466 callContext.procRef, *intrinsic, converter));
2467 Fortran::lower::PreparedActualArguments loweredActuals;
2468
2469 // callback for optional arguments
2470 auto prepareOptionalArg = [&](const Fortran::lower::SomeExpr &expr) {
2471 hlfir::EntityWithAttributes actual = Fortran::lower::convertExprToHLFIR(
2472 loc, converter, expr, callContext.symMap, callContext.stmtCtx);
2473 mlir::Value isPresent =
2474 genIsPresentIfArgMaybeAbsent(loc, actual, expr, callContext,
2475 /*passAsAllocatableOrPointer*/ false)
2476 .value();
2477 loweredActuals.emplace_back(
2478 Fortran::lower::PreparedActualArgument{actual, {isPresent}});
2479 };
2480
2481 // callback for non-optional arguments
2482 auto prepareOtherArg = [&](const Fortran::lower::SomeExpr &expr,
2483 fir::LowerIntrinsicArgAs lowerAs) {
2484 auto getActualFortranElementType = [&]() -> mlir::Type {
2485 return hlfir::getFortranElementType(converter.genType(expr));
2486 };
2487 hlfir::EntityWithAttributes actual = Fortran::lower::convertExprToHLFIR(
2488 loc, converter, expr, callContext.symMap, callContext.stmtCtx);
2489 std::optional<fir::ExtendedValue> exv;
2490 switch (lowerAs) {
2491 case fir::LowerIntrinsicArgAs::Value:
2492 exv = Fortran::lower::convertToValue(loc, converter, actual, stmtCtx);
2493 break;
2494 case fir::LowerIntrinsicArgAs::Addr:
2495 exv = Fortran::lower::convertToAddress(loc, converter, actual, stmtCtx,
2496 getActualFortranElementType());
2497 break;
2498 case fir::LowerIntrinsicArgAs::Box:
2499 exv = Fortran::lower::convertToBox(loc, converter, actual, stmtCtx,
2500 getActualFortranElementType());
2501 break;
2502 case fir::LowerIntrinsicArgAs::Inquired:
2503 exv = Fortran::lower::translateToExtendedValue(loc, builder, actual,
2504 stmtCtx);
2505 break;
2506 }
2507 if (!exv)
2508 llvm_unreachable("bad switch");
2509 actual = extendedValueToHlfirEntity(loc, builder, exv.value(),
2510 "tmp.custom_intrinsic_arg");
2511 loweredActuals.emplace_back(Fortran::lower::PreparedActualArgument{
2512 actual, /*isPresent=*/std::nullopt});
2513 };
2514
2515 Fortran::lower::prepareCustomIntrinsicArgument(
2516 callContext.procRef, *intrinsic, callContext.resultType,
2517 prepareOptionalArg, prepareOtherArg, converter);
2518
2519 return genCustomIntrinsicRefCore(loweredActuals, intrinsic, callContext);
2520 }
2521
2522 /// Lower an intrinsic procedure reference.
2523 /// \p intrinsic is null if this is an intrinsic module procedure that must be
2524 /// lowered as if it were an intrinsic module procedure (like C_LOC which is a
2525 /// procedure from intrinsic module iso_c_binding). Otherwise, \p intrinsic
2526 /// must not be null.
2527
2528 static std::optional<hlfir::EntityWithAttributes>
2529 genIntrinsicRef(const Fortran::evaluate::SpecificIntrinsic *intrinsic,
2530 const fir::IntrinsicHandlerEntry &intrinsicEntry,
2531 CallContext &callContext) {
2532 mlir::Location loc = callContext.loc;
2533 Fortran::lower::PreparedActualArguments loweredActuals;
2534 const fir::IntrinsicArgumentLoweringRules *argLowering =
2535 intrinsicEntry.getArgumentLoweringRules();
2536 for (const auto &arg : llvm::enumerate(callContext.procRef.arguments())) {
2537
2538 if (!arg.value()) {
2539 // Absent optional.
2540 loweredActuals.push_back(std::nullopt);
2541 continue;
2542 }
2543 auto *expr =
2544 Fortran::evaluate::UnwrapExpr<Fortran::lower::SomeExpr>(arg.value());
2545 if (!expr) {
2546 // TYPE(*) dummy. They are only allowed as argument of a few intrinsics
2547 // that do not take optional arguments: see Fortran 2018 standard C710.
2548 const Fortran::evaluate::Symbol *assumedTypeSym =
2549 arg.value()->GetAssumedTypeDummy();
2550 if (!assumedTypeSym)
2551 fir::emitFatalError(loc,
2552 "expected assumed-type symbol as actual argument");
2553 std::optional<fir::FortranVariableOpInterface> var =
2554 callContext.symMap.lookupVariableDefinition(*assumedTypeSym);
2555 if (!var)
2556 fir::emitFatalError(loc, "assumed-type symbol was not lowered");
2557 assert(
2558 (!argLowering ||
2559 !fir::lowerIntrinsicArgumentAs(*argLowering, arg.index())
2560 .handleDynamicOptional) &&
2561 "TYPE(*) are not expected to appear as optional intrinsic arguments");
2562 loweredActuals.push_back(Fortran::lower::PreparedActualArgument{
2563 hlfir::Entity{*var}, /*isPresent=*/std::nullopt});
2564 continue;
2565 }
2566 auto loweredActual = Fortran::lower::convertExprToHLFIR(
2567 loc, callContext.converter, *expr, callContext.symMap,
2568 callContext.stmtCtx);
2569 std::optional<mlir::Value> isPresent;
2570 if (argLowering) {
2571 fir::ArgLoweringRule argRules =
2572 fir::lowerIntrinsicArgumentAs(*argLowering, arg.index());
2573 if (argRules.handleDynamicOptional)
2574 isPresent =
2575 genIsPresentIfArgMaybeAbsent(loc, loweredActual, *expr, callContext,
2576 /*passAsAllocatableOrPointer=*/false);
2577 }
2578 loweredActuals.push_back(
2579 Fortran::lower::PreparedActualArgument{loweredActual, isPresent});
2580 }
2581
2582 if (callContext.isElementalProcWithArrayArgs()) {
2583 // All intrinsic elemental functions are pure.
2584 const bool isFunction = callContext.resultType.has_value();
2585 return ElementalIntrinsicCallBuilder{intrinsic, intrinsicEntry, isFunction}
2586 .genElementalCall(loweredActuals, /*isImpure=*/!isFunction,
2587 callContext);
2588 }
2589 std::optional<hlfir::EntityWithAttributes> result = genHLFIRIntrinsicRefCore(
2590 loweredActuals, intrinsic, intrinsicEntry, callContext);
2591 if (result && mlir::isa<hlfir::ExprType>(result->getType())) {
2592 fir::FirOpBuilder *bldr = &callContext.getBuilder();
2593 callContext.stmtCtx.attachCleanup(
2594 [=]() { bldr->create<hlfir::DestroyOp>(loc, *result); });
2595 }
2596 return result;
2597 }
2598
2599 static std::optional<hlfir::EntityWithAttributes>
2600 genIntrinsicRef(const Fortran::evaluate::SpecificIntrinsic *intrinsic,
2601 CallContext &callContext) {
2602 mlir::Location loc = callContext.loc;
2603 auto &converter = callContext.converter;
2604 if (intrinsic && Fortran::lower::intrinsicRequiresCustomOptionalHandling(
2605 callContext.procRef, *intrinsic, converter)) {
2606 if (callContext.isElementalProcWithArrayArgs())
2607 return genCustomElementalIntrinsicRef(intrinsic, callContext);
2608 return genCustomIntrinsicRef(intrinsic, callContext);
2609 }
2610 std::optional<fir::IntrinsicHandlerEntry> intrinsicEntry =
2611 fir::lookupIntrinsicHandler(callContext.getBuilder(),
2612 callContext.getProcedureName(),
2613 callContext.resultType);
2614 if (!intrinsicEntry)
2615 fir::crashOnMissingIntrinsic(loc, callContext.getProcedureName());
2616 return genIntrinsicRef(intrinsic, *intrinsicEntry, callContext);
2617 }
2618
2619 /// Main entry point to lower procedure references, regardless of what they are.
2620 static std::optional<hlfir::EntityWithAttributes>
2621 genProcedureRef(CallContext &callContext) {
2622 mlir::Location loc = callContext.loc;
2623 fir::FirOpBuilder &builder = callContext.getBuilder();
2624 if (auto *intrinsic = callContext.procRef.proc().GetSpecificIntrinsic())
2625 return genIntrinsicRef(intrinsic, callContext);
2626 // Intercept non BIND(C) module procedure reference that have lowering
2627 // handlers defined for there name. Otherwise, lower them as user
2628 // procedure calls and expect the implementation to be part of
2629 // runtime libraries with the proper name mangling.
2630 if (Fortran::lower::isIntrinsicModuleProcRef(callContext.procRef) &&
2631 !callContext.isBindcCall())
2632 if (std::optional<fir::IntrinsicHandlerEntry> intrinsicEntry =
2633 fir::lookupIntrinsicHandler(builder, callContext.getProcedureName(),
2634 callContext.resultType))
2635 return genIntrinsicRef(nullptr, *intrinsicEntry, callContext);
2636
2637 if (callContext.isStatementFunctionCall())
2638 return genStmtFunctionRef(loc, callContext.converter, callContext.symMap,
2639 callContext.stmtCtx, callContext.procRef);
2640
2641 Fortran::lower::CallerInterface caller(callContext.procRef,
2642 callContext.converter);
2643 mlir::FunctionType callSiteType = caller.genFunctionType();
2644 const bool isElemental = callContext.isElementalProcWithArrayArgs();
2645 Fortran::lower::PreparedActualArguments loweredActuals;
2646 // Lower the actual arguments
2647 for (const Fortran::lower::CallInterface<
2648 Fortran::lower::CallerInterface>::PassedEntity &arg :
2649 caller.getPassedArguments())
2650 if (const auto *actual = arg.entity) {
2651 const auto *expr = actual->UnwrapExpr();
2652 if (!expr) {
2653 // TYPE(*) actual argument.
2654 const Fortran::evaluate::Symbol *assumedTypeSym =
2655 actual->GetAssumedTypeDummy();
2656 if (!assumedTypeSym)
2657 fir::emitFatalError(
2658 loc, "expected assumed-type symbol as actual argument");
2659 std::optional<fir::FortranVariableOpInterface> var =
2660 callContext.symMap.lookupVariableDefinition(*assumedTypeSym);
2661 if (!var)
2662 fir::emitFatalError(loc, "assumed-type symbol was not lowered");
2663 hlfir::Entity actual{*var};
2664 std::optional<mlir::Value> isPresent;
2665 if (arg.isOptional()) {
2666 // Passing an optional TYPE(*) to an optional TYPE(*). Note that
2667 // TYPE(*) cannot be ALLOCATABLE/POINTER (C709) so there is no
2668 // need to cover the case of passing an ALLOCATABLE/POINTER to an
2669 // OPTIONAL.
2670 isPresent =
2671 builder.create<fir::IsPresentOp>(loc, builder.getI1Type(), actual)
2672 .getResult();
2673 }
2674 loweredActuals.push_back(Fortran::lower::PreparedActualArgument{
2675 hlfir::Entity{*var}, isPresent});
2676 continue;
2677 }
2678
2679 if (Fortran::evaluate::UnwrapExpr<Fortran::evaluate::NullPointer>(
2680 *expr)) {
2681 if ((arg.passBy !=
2682 Fortran::lower::CallerInterface::PassEntityBy::MutableBox) &&
2683 (arg.passBy !=
2684 Fortran::lower::CallerInterface::PassEntityBy::BoxProcRef)) {
2685 assert(
2686 arg.isOptional() &&
2687 "NULL must be passed only to pointer, allocatable, or OPTIONAL");
2688 // Trying to lower NULL() outside of any context would lead to
2689 // trouble. NULL() here is equivalent to not providing the
2690 // actual argument.
2691 loweredActuals.emplace_back(std::nullopt);
2692 continue;
2693 }
2694 }
2695
2696 if (isElemental && !arg.hasValueAttribute() &&
2697 Fortran::evaluate::IsVariable(*expr) &&
2698 Fortran::evaluate::HasVectorSubscript(*expr)) {
2699 // Vector subscripted arguments are copied in calls, except in elemental
2700 // calls without VALUE attribute where Fortran 2018 15.5.2.4 point 21
2701 // does not apply and the address of each element must be passed.
2702 hlfir::ElementalAddrOp elementalAddr =
2703 Fortran::lower::convertVectorSubscriptedExprToElementalAddr(
2704 loc, callContext.converter, *expr, callContext.symMap,
2705 callContext.stmtCtx);
2706 loweredActuals.emplace_back(
2707 Fortran::lower::PreparedActualArgument{elementalAddr});
2708 continue;
2709 }
2710
2711 auto loweredActual = Fortran::lower::convertExprToHLFIR(
2712 loc, callContext.converter, *expr, callContext.symMap,
2713 callContext.stmtCtx);
2714 std::optional<mlir::Value> isPresent;
2715 if (arg.isOptional())
2716 isPresent = genIsPresentIfArgMaybeAbsent(
2717 loc, loweredActual, *expr, callContext,
2718 arg.passBy ==
2719 Fortran::lower::CallerInterface::PassEntityBy::MutableBox);
2720
2721 loweredActuals.emplace_back(
2722 Fortran::lower::PreparedActualArgument{loweredActual, isPresent});
2723 } else {
2724 // Optional dummy argument for which there is no actual argument.
2725 loweredActuals.emplace_back(std::nullopt);
2726 }
2727 if (isElemental) {
2728 bool isImpure = false;
2729 if (const Fortran::semantics::Symbol *procSym =
2730 callContext.procRef.proc().GetSymbol())
2731 isImpure = !Fortran::semantics::IsPureProcedure(*procSym);
2732 return ElementalUserCallBuilder{caller, callSiteType}.genElementalCall(
2733 loweredActuals, isImpure, callContext);
2734 }
2735 return genUserCall(loweredActuals, caller, callSiteType, callContext);
2736 }
2737
2738 hlfir::Entity Fortran::lower::PreparedActualArgument::getActual(
2739 mlir::Location loc, fir::FirOpBuilder &builder) const {
2740 if (auto *actualEntity = std::get_if<hlfir::Entity>(&actual)) {
2741 if (oneBasedElementalIndices)
2742 return hlfir::getElementAt(loc, builder, *actualEntity,
2743 *oneBasedElementalIndices);
2744 return *actualEntity;
2745 }
2746 assert(oneBasedElementalIndices && "expect elemental context");
2747 hlfir::ElementalAddrOp elementalAddr =
2748 std::get<hlfir::ElementalAddrOp>(actual);
2749 mlir::IRMapping mapper;
2750 auto alwaysFalse = [](hlfir::ElementalOp) -> bool { return false; };
2751 mlir::Value addr = hlfir::inlineElementalOp(
2752 loc, builder, elementalAddr, *oneBasedElementalIndices, mapper,
2753 /*mustRecursivelyInline=*/alwaysFalse);
2754 assert(elementalAddr.getCleanup().empty() && "no clean-up expected");
2755 elementalAddr.erase();
2756 return hlfir::Entity{addr};
2757 }
2758
2759 bool Fortran::lower::isIntrinsicModuleProcRef(
2760 const Fortran::evaluate::ProcedureRef &procRef) {
2761 const Fortran::semantics::Symbol *symbol = procRef.proc().GetSymbol();
2762 if (!symbol)
2763 return false;
2764 const Fortran::semantics::Symbol *module =
2765 symbol->GetUltimate().owner().GetSymbol();
2766 return module && module->attrs().test(Fortran::semantics::Attr::INTRINSIC);
2767 }
2768
2769 static bool isInWhereMaskedExpression(fir::FirOpBuilder &builder) {
2770 // The MASK of the outer WHERE is not masked itself.
2771 mlir::Operation *op = builder.getRegion().getParentOp();
2772 return op && op->getParentOfType<hlfir::WhereOp>();
2773 }
2774
2775 std::optional<hlfir::EntityWithAttributes> Fortran::lower::convertCallToHLFIR(
2776 mlir::Location loc, Fortran::lower::AbstractConverter &converter,
2777 const evaluate::ProcedureRef &procRef, std::optional<mlir::Type> resultType,
2778 Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx) {
2779 auto &builder = converter.getFirOpBuilder();
2780 if (resultType && !procRef.IsElemental() &&
2781 isInWhereMaskedExpression(builder) &&
2782 !builder.getRegion().getParentOfType<hlfir::ExactlyOnceOp>()) {
2783 // Non elemental calls inside a where-assignment-stmt must be executed
2784 // exactly once without mask control. Lower them in a special region so that
2785 // this can be enforced whenscheduling forall/where expression evaluations.
2786 Fortran::lower::StatementContext localStmtCtx;
2787 mlir::Type bogusType = builder.getIndexType();
2788 auto exactlyOnce = builder.create<hlfir::ExactlyOnceOp>(loc, bogusType);
2789 mlir::Block *block = builder.createBlock(&exactlyOnce.getBody());
2790 builder.setInsertionPointToStart(block);
2791 CallContext callContext(procRef, resultType, loc, converter, symMap,
2792 localStmtCtx);
2793 std::optional<hlfir::EntityWithAttributes> res =
2794 genProcedureRef(callContext);
2795 assert(res.has_value() && "must be a function");
2796 auto yield = builder.create<hlfir::YieldOp>(loc, *res);
2797 Fortran::lower::genCleanUpInRegionIfAny(loc, builder, yield.getCleanup(),
2798 localStmtCtx);
2799 builder.setInsertionPointAfter(exactlyOnce);
2800 exactlyOnce->getResult(0).setType(res->getType());
2801 if (hlfir::isFortranValue(exactlyOnce.getResult()))
2802 return hlfir::EntityWithAttributes{exactlyOnce.getResult()};
2803 // Create hlfir.declare for the result to satisfy
2804 // hlfir::EntityWithAttributes requirements.
2805 auto [exv, cleanup] = hlfir::translateToExtendedValue(
2806 loc, builder, hlfir::Entity{exactlyOnce});
2807 assert(!cleanup && "resut is a variable");
2808 return hlfir::genDeclare(loc, builder, exv, ".func.pointer.result",
2809 fir::FortranVariableFlagsAttr{});
2810 }
2811 CallContext callContext(procRef, resultType, loc, converter, symMap, stmtCtx);
2812 return genProcedureRef(callContext);
2813 }
2814
2815 void Fortran::lower::convertUserDefinedAssignmentToHLFIR(
2816 mlir::Location loc, Fortran::lower::AbstractConverter &converter,
2817 const evaluate::ProcedureRef &procRef, hlfir::Entity lhs, hlfir::Entity rhs,
2818 Fortran::lower::SymMap &symMap) {
2819 Fortran::lower::StatementContext definedAssignmentContext;
2820 CallContext callContext(procRef, /*resultType=*/std::nullopt, loc, converter,
2821 symMap, definedAssignmentContext);
2822 Fortran::lower::CallerInterface caller(procRef, converter);
2823 mlir::FunctionType callSiteType = caller.genFunctionType();
2824 PreparedActualArgument preparedLhs{lhs, /*isPresent=*/std::nullopt};
2825 PreparedActualArgument preparedRhs{rhs, /*isPresent=*/std::nullopt};
2826 PreparedActualArguments loweredActuals{preparedLhs, preparedRhs};
2827 genUserCall(loweredActuals, caller, callSiteType, callContext);
2828 return;
2829 }