Debian Codegraph @

flang/lib/Lower/Allocatable.cpp

raw
1 //===-- Allocatable.cpp -- Allocatable statements lowering ----------------===//
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/Allocatable.h"
14 #include "flang/Evaluate/tools.h"
15 #include "flang/Lower/AbstractConverter.h"
16 #include "flang/Lower/ConvertType.h"
17 #include "flang/Lower/ConvertVariable.h"
18 #include "flang/Lower/IterationSpace.h"
19 #include "flang/Lower/Mangler.h"
20 #include "flang/Lower/OpenACC.h"
21 #include "flang/Lower/PFTBuilder.h"
22 #include "flang/Lower/Runtime.h"
23 #include "flang/Lower/StatementContext.h"
24 #include "flang/Optimizer/Builder/FIRBuilder.h"
25 #include "flang/Optimizer/Builder/Runtime/RTBuilder.h"
26 #include "flang/Optimizer/Builder/Todo.h"
27 #include "flang/Optimizer/Dialect/CUF/CUFOps.h"
28 #include "flang/Optimizer/Dialect/FIROps.h"
29 #include "flang/Optimizer/Dialect/FIROpsSupport.h"
30 #include "flang/Optimizer/Support/FatalError.h"
31 #include "flang/Optimizer/Support/InternalNames.h"
32 #include "flang/Parser/parse-tree.h"
33 #include "flang/Runtime/allocatable.h"
34 #include "flang/Runtime/pointer.h"
35 #include "flang/Semantics/tools.h"
36 #include "flang/Semantics/type.h"
37 #include "llvm/Support/CommandLine.h"
38
39 /// By default fir memory operation fir::AllocMemOp/fir::FreeMemOp are used.
40 /// This switch allow forcing the use of runtime and descriptors for everything.
41 /// This is mainly intended as a debug switch.
42 static llvm::cl::opt<bool> useAllocateRuntime(
43 "use-alloc-runtime",
44 llvm::cl::desc("Lower allocations to fortran runtime calls"),
45 llvm::cl::init(false));
46 /// Switch to force lowering of allocatable and pointers to descriptors in all
47 /// cases. This is now turned on by default since that is what will happen with
48 /// HLFIR lowering, so this allows getting early feedback of the impact.
49 /// If this turns out to cause performance regressions, a dedicated fir.box
50 /// "discretization pass" would make more sense to cover all the fir.box usage
51 /// (taking advantage of any future inlining for instance).
52 static llvm::cl::opt<bool> useDescForMutableBox(
53 "use-desc-for-alloc",
54 llvm::cl::desc("Always use descriptors for POINTER and ALLOCATABLE"),
55 llvm::cl::init(true));
56
57 //===----------------------------------------------------------------------===//
58 // Error management
59 //===----------------------------------------------------------------------===//
60
61 namespace {
62 // Manage STAT and ERRMSG specifier information across a sequence of runtime
63 // calls for an ALLOCATE/DEALLOCATE stmt.
64 struct ErrorManager {
65 void init(Fortran::lower::AbstractConverter &converter, mlir::Location loc,
66 const Fortran::lower::SomeExpr *statExpr,
67 const Fortran::lower::SomeExpr *errMsgExpr) {
68 Fortran::lower::StatementContext stmtCtx;
69 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
70 hasStat = builder.createBool(loc, statExpr != nullptr);
71 statAddr = statExpr
72 ? fir::getBase(converter.genExprAddr(loc, statExpr, stmtCtx))
73 : mlir::Value{};
74 errMsgAddr =
75 statExpr && errMsgExpr
76 ? builder.createBox(loc,
77 converter.genExprAddr(loc, errMsgExpr, stmtCtx))
78 : builder.create<fir::AbsentOp>(
79 loc,
80 fir::BoxType::get(mlir::NoneType::get(builder.getContext())));
81 sourceFile = fir::factory::locationToFilename(builder, loc);
82 sourceLine = fir::factory::locationToLineNo(builder, loc,
83 builder.getIntegerType(32));
84 }
85
86 bool hasStatSpec() const { return static_cast<bool>(statAddr); }
87
88 void genStatCheck(fir::FirOpBuilder &builder, mlir::Location loc) {
89 if (statValue) {
90 mlir::Value zero =
91 builder.createIntegerConstant(loc, statValue.getType(), 0);
92 auto cmp = builder.create<mlir::arith::CmpIOp>(
93 loc, mlir::arith::CmpIPredicate::eq, statValue, zero);
94 auto ifOp = builder.create<fir::IfOp>(loc, cmp,
95 /*withElseRegion=*/false);
96 builder.setInsertionPointToStart(&ifOp.getThenRegion().front());
97 }
98 }
99
100 void assignStat(fir::FirOpBuilder &builder, mlir::Location loc,
101 mlir::Value stat) {
102 if (hasStatSpec()) {
103 assert(stat && "missing stat value");
104 mlir::Value castStat = builder.createConvert(
105 loc, fir::dyn_cast_ptrEleTy(statAddr.getType()), stat);
106 builder.create<fir::StoreOp>(loc, castStat, statAddr);
107 statValue = stat;
108 }
109 }
110
111 mlir::Value hasStat;
112 mlir::Value errMsgAddr;
113 mlir::Value sourceFile;
114 mlir::Value sourceLine;
115
116 private:
117 mlir::Value statAddr; // STAT variable address
118 mlir::Value statValue; // current runtime STAT value
119 };
120
121 //===----------------------------------------------------------------------===//
122 // Allocatables runtime call generators
123 //===----------------------------------------------------------------------===//
124
125 using namespace Fortran::runtime;
126 /// Generate a runtime call to set the bounds of an allocatable or pointer
127 /// descriptor.
128 static void genRuntimeSetBounds(fir::FirOpBuilder &builder, mlir::Location loc,
129 const fir::MutableBoxValue &box,
130 mlir::Value dimIndex, mlir::Value lowerBound,
131 mlir::Value upperBound) {
132 mlir::func::FuncOp callee =
133 box.isPointer()
134 ? fir::runtime::getRuntimeFunc<mkRTKey(PointerSetBounds)>(loc,
135 builder)
136 : fir::runtime::getRuntimeFunc<mkRTKey(AllocatableSetBounds)>(
137 loc, builder);
138 llvm::SmallVector<mlir::Value> args{box.getAddr(), dimIndex, lowerBound,
139 upperBound};
140 llvm::SmallVector<mlir::Value> operands;
141 for (auto [fst, snd] : llvm::zip(args, callee.getFunctionType().getInputs()))
142 operands.emplace_back(builder.createConvert(loc, snd, fst));
143 builder.create<fir::CallOp>(loc, callee, operands);
144 }
145
146 /// Generate runtime call to set the lengths of a character allocatable or
147 /// pointer descriptor.
148 static void genRuntimeInitCharacter(fir::FirOpBuilder &builder,
149 mlir::Location loc,
150 const fir::MutableBoxValue &box,
151 mlir::Value len, int64_t kind = 0) {
152 mlir::func::FuncOp callee =
153 box.isPointer()
154 ? fir::runtime::getRuntimeFunc<mkRTKey(PointerNullifyCharacter)>(
155 loc, builder)
156 : fir::runtime::getRuntimeFunc<mkRTKey(
157 AllocatableInitCharacterForAllocate)>(loc, builder);
158 llvm::ArrayRef<mlir::Type> inputTypes = callee.getFunctionType().getInputs();
159 if (inputTypes.size() != 5)
160 fir::emitFatalError(
161 loc, "AllocatableInitCharacter runtime interface not as expected");
162 llvm::SmallVector<mlir::Value> args;
163 args.push_back(builder.createConvert(loc, inputTypes[0], box.getAddr()));
164 args.push_back(builder.createConvert(loc, inputTypes[1], len));
165 if (kind == 0)
166 kind = mlir::cast<fir::CharacterType>(box.getEleTy()).getFKind();
167 args.push_back(builder.createIntegerConstant(loc, inputTypes[2], kind));
168 int rank = box.rank();
169 args.push_back(builder.createIntegerConstant(loc, inputTypes[3], rank));
170 // TODO: coarrays
171 int corank = 0;
172 args.push_back(builder.createIntegerConstant(loc, inputTypes[4], corank));
173 builder.create<fir::CallOp>(loc, callee, args);
174 }
175
176 /// Generate a sequence of runtime calls to allocate memory.
177 static mlir::Value genRuntimeAllocate(fir::FirOpBuilder &builder,
178 mlir::Location loc,
179 const fir::MutableBoxValue &box,
180 ErrorManager &errorManager) {
181 mlir::func::FuncOp callee =
182 box.isPointer()
183 ? fir::runtime::getRuntimeFunc<mkRTKey(PointerAllocate)>(loc, builder)
184 : fir::runtime::getRuntimeFunc<mkRTKey(AllocatableAllocate)>(loc,
185 builder);
186 llvm::SmallVector<mlir::Value> args{
187 box.getAddr(), errorManager.hasStat, errorManager.errMsgAddr,
188 errorManager.sourceFile, errorManager.sourceLine};
189 llvm::SmallVector<mlir::Value> operands;
190 for (auto [fst, snd] : llvm::zip(args, callee.getFunctionType().getInputs()))
191 operands.emplace_back(builder.createConvert(loc, snd, fst));
192 return builder.create<fir::CallOp>(loc, callee, operands).getResult(0);
193 }
194
195 /// Generate a sequence of runtime calls to allocate memory and assign with the
196 /// \p source.
197 static mlir::Value genRuntimeAllocateSource(fir::FirOpBuilder &builder,
198 mlir::Location loc,
199 const fir::MutableBoxValue &box,
200 fir::ExtendedValue source,
201 ErrorManager &errorManager) {
202 mlir::func::FuncOp callee =
203 box.isPointer()
204 ? fir::runtime::getRuntimeFunc<mkRTKey(PointerAllocateSource)>(
205 loc, builder)
206 : fir::runtime::getRuntimeFunc<mkRTKey(AllocatableAllocateSource)>(
207 loc, builder);
208 llvm::SmallVector<mlir::Value> args{
209 box.getAddr(), fir::getBase(source),
210 errorManager.hasStat, errorManager.errMsgAddr,
211 errorManager.sourceFile, errorManager.sourceLine};
212 llvm::SmallVector<mlir::Value> operands;
213 for (auto [fst, snd] : llvm::zip(args, callee.getFunctionType().getInputs()))
214 operands.emplace_back(builder.createConvert(loc, snd, fst));
215 return builder.create<fir::CallOp>(loc, callee, operands).getResult(0);
216 }
217
218 /// Generate runtime call to apply mold to the descriptor.
219 static void genRuntimeAllocateApplyMold(fir::FirOpBuilder &builder,
220 mlir::Location loc,
221 const fir::MutableBoxValue &box,
222 fir::ExtendedValue mold, int rank) {
223 mlir::func::FuncOp callee =
224 box.isPointer()
225 ? fir::runtime::getRuntimeFunc<mkRTKey(PointerApplyMold)>(loc,
226 builder)
227 : fir::runtime::getRuntimeFunc<mkRTKey(AllocatableApplyMold)>(
228 loc, builder);
229 llvm::SmallVector<mlir::Value> args{
230 fir::factory::getMutableIRBox(builder, loc, box), fir::getBase(mold),
231 builder.createIntegerConstant(
232 loc, callee.getFunctionType().getInputs()[2], rank)};
233 llvm::SmallVector<mlir::Value> operands;
234 for (auto [fst, snd] : llvm::zip(args, callee.getFunctionType().getInputs()))
235 operands.emplace_back(builder.createConvert(loc, snd, fst));
236 builder.create<fir::CallOp>(loc, callee, operands);
237 }
238
239 /// Generate a runtime call to deallocate memory.
240 static mlir::Value genRuntimeDeallocate(fir::FirOpBuilder &builder,
241 mlir::Location loc,
242 const fir::MutableBoxValue &box,
243 ErrorManager &errorManager,
244 mlir::Value declaredTypeDesc = {}) {
245 // Ensure fir.box is up-to-date before passing it to deallocate runtime.
246 mlir::Value boxAddress = fir::factory::getMutableIRBox(builder, loc, box);
247 mlir::func::FuncOp callee;
248 llvm::SmallVector<mlir::Value> args;
249 llvm::SmallVector<mlir::Value> operands;
250 if (box.isPolymorphic() || box.isUnlimitedPolymorphic()) {
251 callee = box.isPointer()
252 ? fir::runtime::getRuntimeFunc<mkRTKey(
253 PointerDeallocatePolymorphic)>(loc, builder)
254 : fir::runtime::getRuntimeFunc<mkRTKey(
255 AllocatableDeallocatePolymorphic)>(loc, builder);
256 if (!declaredTypeDesc)
257 declaredTypeDesc = builder.createNullConstant(loc);
258 operands = fir::runtime::createArguments(
259 builder, loc, callee.getFunctionType(), boxAddress, declaredTypeDesc,
260 errorManager.hasStat, errorManager.errMsgAddr, errorManager.sourceFile,
261 errorManager.sourceLine);
262 } else {
263 callee = box.isPointer()
264 ? fir::runtime::getRuntimeFunc<mkRTKey(PointerDeallocate)>(
265 loc, builder)
266 : fir::runtime::getRuntimeFunc<mkRTKey(AllocatableDeallocate)>(
267 loc, builder);
268 operands = fir::runtime::createArguments(
269 builder, loc, callee.getFunctionType(), boxAddress,
270 errorManager.hasStat, errorManager.errMsgAddr, errorManager.sourceFile,
271 errorManager.sourceLine);
272 }
273 return builder.create<fir::CallOp>(loc, callee, operands).getResult(0);
274 }
275
276 //===----------------------------------------------------------------------===//
277 // Allocate statement implementation
278 //===----------------------------------------------------------------------===//
279
280 /// Helper to get symbol from AllocateObject.
281 static const Fortran::semantics::Symbol &
282 unwrapSymbol(const Fortran::parser::AllocateObject &allocObj) {
283 const Fortran::parser::Name &lastName =
284 Fortran::parser::GetLastName(allocObj);
285 assert(lastName.symbol);
286 return *lastName.symbol;
287 }
288
289 static fir::MutableBoxValue
290 genMutableBoxValue(Fortran::lower::AbstractConverter &converter,
291 mlir::Location loc,
292 const Fortran::parser::AllocateObject &allocObj) {
293 const Fortran::lower::SomeExpr *expr = Fortran::semantics::GetExpr(allocObj);
294 assert(expr && "semantic analysis failure");
295 return converter.genExprMutableBox(loc, *expr);
296 }
297
298 /// Implement Allocate statement lowering.
299 class AllocateStmtHelper {
300 public:
301 AllocateStmtHelper(Fortran::lower::AbstractConverter &converter,
302 const Fortran::parser::AllocateStmt &stmt,
303 mlir::Location loc)
304 : converter{converter}, builder{converter.getFirOpBuilder()}, stmt{stmt},
305 loc{loc} {}
306
307 void lower() {
308 visitAllocateOptions();
309 lowerAllocateLengthParameters();
310 errorManager.init(converter, loc, statExpr, errMsgExpr);
311 Fortran::lower::StatementContext stmtCtx;
312 if (sourceExpr)
313 sourceExv = converter.genExprBox(loc, *sourceExpr, stmtCtx);
314 if (moldExpr)
315 moldExv = converter.genExprBox(loc, *moldExpr, stmtCtx);
316 mlir::OpBuilder::InsertPoint insertPt = builder.saveInsertionPoint();
317 for (const auto &allocation :
318 std::get<std::list<Fortran::parser::Allocation>>(stmt.t))
319 lowerAllocation(unwrapAllocation(allocation));
320 builder.restoreInsertionPoint(insertPt);
321 }
322
323 private:
324 struct Allocation {
325 const Fortran::parser::Allocation &alloc;
326 const Fortran::semantics::DeclTypeSpec &type;
327 bool hasCoarraySpec() const {
328 return std::get<std::optional<Fortran::parser::AllocateCoarraySpec>>(
329 alloc.t)
330 .has_value();
331 }
332 const Fortran::parser::AllocateObject &getAllocObj() const {
333 return std::get<Fortran::parser::AllocateObject>(alloc.t);
334 }
335 const Fortran::semantics::Symbol &getSymbol() const {
336 return unwrapSymbol(getAllocObj());
337 }
338 const std::list<Fortran::parser::AllocateShapeSpec> &getShapeSpecs() const {
339 return std::get<std::list<Fortran::parser::AllocateShapeSpec>>(alloc.t);
340 }
341 };
342
343 Allocation unwrapAllocation(const Fortran::parser::Allocation &alloc) {
344 const auto &allocObj = std::get<Fortran::parser::AllocateObject>(alloc.t);
345 const Fortran::semantics::Symbol &symbol = unwrapSymbol(allocObj);
346 assert(symbol.GetType());
347 return Allocation{alloc, *symbol.GetType()};
348 }
349
350 void visitAllocateOptions() {
351 for (const auto &allocOption :
352 std::get<std::list<Fortran::parser::AllocOpt>>(stmt.t))
353 Fortran::common::visit(
354 Fortran::common::visitors{
355 [&](const Fortran::parser::StatOrErrmsg &statOrErr) {
356 Fortran::common::visit(
357 Fortran::common::visitors{
358 [&](const Fortran::parser::StatVariable &statVar) {
359 statExpr = Fortran::semantics::GetExpr(statVar);
360 },
361 [&](const Fortran::parser::MsgVariable &errMsgVar) {
362 errMsgExpr = Fortran::semantics::GetExpr(errMsgVar);
363 },
364 },
365 statOrErr.u);
366 },
367 [&](const Fortran::parser::AllocOpt::Source &source) {
368 sourceExpr = Fortran::semantics::GetExpr(source.v.value());
369 },
370 [&](const Fortran::parser::AllocOpt::Mold &mold) {
371 moldExpr = Fortran::semantics::GetExpr(mold.v.value());
372 },
373 [&](const Fortran::parser::AllocOpt::Stream &stream) {
374 streamExpr = Fortran::semantics::GetExpr(stream.v.value());
375 },
376 [&](const Fortran::parser::AllocOpt::Pinned &pinned) {
377 pinnedExpr = Fortran::semantics::GetExpr(pinned.v.value());
378 },
379 },
380 allocOption.u);
381 }
382
383 void lowerAllocation(const Allocation &alloc) {
384 fir::MutableBoxValue boxAddr =
385 genMutableBoxValue(converter, loc, alloc.getAllocObj());
386
387 if (sourceExpr)
388 genSourceMoldAllocation(alloc, boxAddr, /*isSource=*/true);
389 else if (moldExpr)
390 genSourceMoldAllocation(alloc, boxAddr, /*isSource=*/false);
391 else
392 genSimpleAllocation(alloc, boxAddr);
393 }
394
395 static bool lowerBoundsAreOnes(const Allocation &alloc) {
396 for (const Fortran::parser::AllocateShapeSpec &shapeSpec :
397 alloc.getShapeSpecs())
398 if (std::get<0>(shapeSpec.t))
399 return false;
400 return true;
401 }
402
403 /// Build name for the fir::allocmem generated for alloc.
404 std::string mangleAlloc(const Allocation &alloc) {
405 return converter.mangleName(alloc.getSymbol()) + ".alloc";
406 }
407
408 /// Generate allocation without runtime calls.
409 /// Only for intrinsic types. No coarrays, no polymorphism. No error recovery.
410 void genInlinedAllocation(const Allocation &alloc,
411 const fir::MutableBoxValue &box) {
412 llvm::SmallVector<mlir::Value> lbounds;
413 llvm::SmallVector<mlir::Value> extents;
414 Fortran::lower::StatementContext stmtCtx;
415 mlir::Type idxTy = builder.getIndexType();
416 bool lBoundsAreOnes = lowerBoundsAreOnes(alloc);
417 mlir::Value one = builder.createIntegerConstant(loc, idxTy, 1);
418 for (const Fortran::parser::AllocateShapeSpec &shapeSpec :
419 alloc.getShapeSpecs()) {
420 mlir::Value lb;
421 if (!lBoundsAreOnes) {
422 if (const std::optional<Fortran::parser::BoundExpr> &lbExpr =
423 std::get<0>(shapeSpec.t)) {
424 lb = fir::getBase(converter.genExprValue(
425 loc, Fortran::semantics::GetExpr(*lbExpr), stmtCtx));
426 lb = builder.createConvert(loc, idxTy, lb);
427 } else {
428 lb = one;
429 }
430 lbounds.emplace_back(lb);
431 }
432 mlir::Value ub = fir::getBase(converter.genExprValue(
433 loc, Fortran::semantics::GetExpr(std::get<1>(shapeSpec.t)), stmtCtx));
434 ub = builder.createConvert(loc, idxTy, ub);
435 if (lb) {
436 mlir::Value diff = builder.create<mlir::arith::SubIOp>(loc, ub, lb);
437 extents.emplace_back(
438 builder.create<mlir::arith::AddIOp>(loc, diff, one));
439 } else {
440 extents.emplace_back(ub);
441 }
442 }
443 fir::factory::genInlinedAllocation(builder, loc, box, lbounds, extents,
444 lenParams, mangleAlloc(alloc),
445 /*mustBeHeap=*/true);
446 }
447
448 void postAllocationAction(const Allocation &alloc) {
449 if (alloc.getSymbol().test(Fortran::semantics::Symbol::Flag::AccDeclare))
450 Fortran::lower::attachDeclarePostAllocAction(converter, builder,
451 alloc.getSymbol());
452 }
453
454 void genSimpleAllocation(const Allocation &alloc,
455 const fir::MutableBoxValue &box) {
456 if (!box.isDerived() && !errorManager.hasStatSpec() &&
457 !alloc.type.IsPolymorphic() && !alloc.hasCoarraySpec() &&
458 !useAllocateRuntime && !box.isPointer() &&
459 !Fortran::semantics::HasCUDAAttr(alloc.getSymbol())) {
460 // Pointers must use PointerAllocate so that their deallocations
461 // can be validated.
462 genInlinedAllocation(alloc, box);
463 postAllocationAction(alloc);
464 return;
465 }
466 // Generate a sequence of runtime calls.
467 errorManager.genStatCheck(builder, loc);
468 genAllocateObjectInit(box);
469 if (alloc.hasCoarraySpec())
470 TODO(loc, "coarray: allocation of a coarray object");
471 if (alloc.type.IsPolymorphic())
472 genSetType(alloc, box, loc);
473 genSetDeferredLengthParameters(alloc, box);
474 genAllocateObjectBounds(alloc, box);
475 mlir::Value stat;
476 if (!Fortran::semantics::HasCUDAAttr(alloc.getSymbol()))
477 stat = genRuntimeAllocate(builder, loc, box, errorManager);
478 else
479 stat =
480 genCudaAllocate(builder, loc, box, errorManager, alloc.getSymbol());
481 fir::factory::syncMutableBoxFromIRBox(builder, loc, box);
482 postAllocationAction(alloc);
483 errorManager.assignStat(builder, loc, stat);
484 }
485
486 /// Lower the length parameters that may be specified in the optional
487 /// type specification.
488 void lowerAllocateLengthParameters() {
489 const Fortran::semantics::DeclTypeSpec *typeSpec =
490 getIfAllocateStmtTypeSpec();
491 if (!typeSpec)
492 return;
493 if (const Fortran::semantics::DerivedTypeSpec *derived =
494 typeSpec->AsDerived())
495 if (Fortran::semantics::CountLenParameters(*derived) > 0)
496 TODO(loc, "setting derived type params in allocation");
497 if (typeSpec->category() ==
498 Fortran::semantics::DeclTypeSpec::Category::Character) {
499 Fortran::semantics::ParamValue lenParam =
500 typeSpec->characterTypeSpec().length();
501 if (Fortran::semantics::MaybeIntExpr intExpr = lenParam.GetExplicit()) {
502 Fortran::lower::StatementContext stmtCtx;
503 Fortran::lower::SomeExpr lenExpr{*intExpr};
504 lenParams.push_back(
505 fir::getBase(converter.genExprValue(loc, lenExpr, stmtCtx)));
506 }
507 }
508 }
509
510 // Set length parameters in the box stored in boxAddr.
511 // This must be called before setting the bounds because it may use
512 // Init runtime calls that may set the bounds to zero.
513 void genSetDeferredLengthParameters(const Allocation &alloc,
514 const fir::MutableBoxValue &box) {
515 if (lenParams.empty())
516 return;
517 // TODO: in case a length parameter was not deferred, insert a runtime check
518 // that the length is the same (AllocatableCheckLengthParameter runtime
519 // call).
520 if (box.isCharacter())
521 genRuntimeInitCharacter(builder, loc, box, lenParams[0]);
522
523 if (box.isDerived())
524 TODO(loc, "derived type length parameters in allocate");
525 }
526
527 void genAllocateObjectInit(const fir::MutableBoxValue &box) {
528 if (box.isPointer()) {
529 // For pointers, the descriptor may still be uninitialized (see Fortran
530 // 2018 19.5.2.2). The allocation runtime needs to be given a descriptor
531 // with initialized rank, types and attributes. Initialize the descriptor
532 // here to ensure these constraints are fulfilled.
533 mlir::Value nullPointer = fir::factory::createUnallocatedBox(
534 builder, loc, box.getBoxTy(), box.nonDeferredLenParams());
535 builder.create<fir::StoreOp>(loc, nullPointer, box.getAddr());
536 } else {
537 assert(box.isAllocatable() && "must be an allocatable");
538 // For allocatables, sync the MutableBoxValue and descriptor before the
539 // calls in case it is tracked locally by a set of variables.
540 fir::factory::getMutableIRBox(builder, loc, box);
541 }
542 }
543
544 void genAllocateObjectBounds(const Allocation &alloc,
545 const fir::MutableBoxValue &box) {
546 // Set bounds for arrays
547 mlir::Type idxTy = builder.getIndexType();
548 mlir::Type i32Ty = builder.getIntegerType(32);
549 Fortran::lower::StatementContext stmtCtx;
550 for (const auto &iter : llvm::enumerate(alloc.getShapeSpecs())) {
551 mlir::Value lb;
552 const auto &bounds = iter.value().t;
553 if (const std::optional<Fortran::parser::BoundExpr> &lbExpr =
554 std::get<0>(bounds))
555 lb = fir::getBase(converter.genExprValue(
556 loc, Fortran::semantics::GetExpr(*lbExpr), stmtCtx));
557 else
558 lb = builder.createIntegerConstant(loc, idxTy, 1);
559 mlir::Value ub = fir::getBase(converter.genExprValue(
560 loc, Fortran::semantics::GetExpr(std::get<1>(bounds)), stmtCtx));
561 mlir::Value dimIndex =
562 builder.createIntegerConstant(loc, i32Ty, iter.index());
563 // Runtime call
564 genRuntimeSetBounds(builder, loc, box, dimIndex, lb, ub);
565 }
566 if (sourceExpr && sourceExpr->Rank() > 0 &&
567 alloc.getShapeSpecs().size() == 0) {
568 // If the alloc object does not have shape list, get the bounds from the
569 // source expression.
570 mlir::Value one = builder.createIntegerConstant(loc, idxTy, 1);
571 const auto *sourceBox = sourceExv.getBoxOf<fir::BoxValue>();
572 assert(sourceBox && "source expression should be lowered to one box");
573 for (int i = 0; i < sourceExpr->Rank(); ++i) {
574 auto dimVal = builder.createIntegerConstant(loc, idxTy, i);
575 auto dimInfo = builder.create<fir::BoxDimsOp>(
576 loc, idxTy, idxTy, idxTy, sourceBox->getAddr(), dimVal);
577 mlir::Value lb =
578 fir::factory::readLowerBound(builder, loc, sourceExv, i, one);
579 mlir::Value extent = dimInfo.getResult(1);
580 mlir::Value ub = builder.create<mlir::arith::SubIOp>(
581 loc, builder.create<mlir::arith::AddIOp>(loc, extent, lb), one);
582 mlir::Value dimIndex = builder.createIntegerConstant(loc, i32Ty, i);
583 genRuntimeSetBounds(builder, loc, box, dimIndex, lb, ub);
584 }
585 }
586 }
587
588 void genSourceMoldAllocation(const Allocation &alloc,
589 const fir::MutableBoxValue &box, bool isSource) {
590 fir::ExtendedValue exv = isSource ? sourceExv : moldExv;
591 ;
592 // Generate a sequence of runtime calls.
593 errorManager.genStatCheck(builder, loc);
594 genAllocateObjectInit(box);
595 if (alloc.hasCoarraySpec())
596 TODO(loc, "coarray: allocation of a coarray object");
597 // Set length of the allocate object if it has. Otherwise, get the length
598 // from source for the deferred length parameter.
599 const bool isDeferredLengthCharacter =
600 box.isCharacter() && !box.hasNonDeferredLenParams();
601 if (lenParams.empty() && isDeferredLengthCharacter)
602 lenParams.push_back(fir::factory::readCharLen(builder, loc, exv));
603 if (!isSource || alloc.type.IsPolymorphic())
604 genRuntimeAllocateApplyMold(builder, loc, box, exv,
605 alloc.getSymbol().Rank());
606 if (isDeferredLengthCharacter)
607 genSetDeferredLengthParameters(alloc, box);
608 genAllocateObjectBounds(alloc, box);
609 mlir::Value stat;
610 if (Fortran::semantics::HasCUDAAttr(alloc.getSymbol()))
611 stat =
612 genCudaAllocate(builder, loc, box, errorManager, alloc.getSymbol());
613 else if (isSource)
614 stat = genRuntimeAllocateSource(builder, loc, box, exv, errorManager);
615 else
616 stat = genRuntimeAllocate(builder, loc, box, errorManager);
617 fir::factory::syncMutableBoxFromIRBox(builder, loc, box);
618 postAllocationAction(alloc);
619 errorManager.assignStat(builder, loc, stat);
620 }
621
622 /// Generate call to PointerNullifyDerived or AllocatableInitDerived
623 /// to set the dynamic type information.
624 void genInitDerived(const fir::MutableBoxValue &box, mlir::Value typeDescAddr,
625 int rank, int corank = 0) {
626 mlir::func::FuncOp callee =
627 box.isPointer()
628 ? fir::runtime::getRuntimeFunc<mkRTKey(PointerNullifyDerived)>(
629 loc, builder)
630 : fir::runtime::getRuntimeFunc<mkRTKey(
631 AllocatableInitDerivedForAllocate)>(loc, builder);
632
633 llvm::ArrayRef<mlir::Type> inputTypes =
634 callee.getFunctionType().getInputs();
635 llvm::SmallVector<mlir::Value> args;
636 args.push_back(builder.createConvert(loc, inputTypes[0], box.getAddr()));
637 args.push_back(builder.createConvert(loc, inputTypes[1], typeDescAddr));
638 mlir::Value rankValue =
639 builder.createIntegerConstant(loc, inputTypes[2], rank);
640 mlir::Value corankValue =
641 builder.createIntegerConstant(loc, inputTypes[3], corank);
642 args.push_back(rankValue);
643 args.push_back(corankValue);
644 builder.create<fir::CallOp>(loc, callee, args);
645 }
646
647 /// Generate call to PointerNullifyIntrinsic or AllocatableInitIntrinsic to
648 /// set the dynamic type information for a polymorphic entity from an
649 /// intrinsic type spec.
650 void genInitIntrinsic(const fir::MutableBoxValue &box,
651 const TypeCategory category, int64_t kind, int rank,
652 int corank = 0) {
653 mlir::func::FuncOp callee =
654 box.isPointer()
655 ? fir::runtime::getRuntimeFunc<mkRTKey(PointerNullifyIntrinsic)>(
656 loc, builder)
657 : fir::runtime::getRuntimeFunc<mkRTKey(
658 AllocatableInitIntrinsicForAllocate)>(loc, builder);
659
660 llvm::ArrayRef<mlir::Type> inputTypes =
661 callee.getFunctionType().getInputs();
662 llvm::SmallVector<mlir::Value> args;
663 args.push_back(builder.createConvert(loc, inputTypes[0], box.getAddr()));
664 mlir::Value categoryValue = builder.createIntegerConstant(
665 loc, inputTypes[1], static_cast<int32_t>(category));
666 mlir::Value kindValue =
667 builder.createIntegerConstant(loc, inputTypes[2], kind);
668 mlir::Value rankValue =
669 builder.createIntegerConstant(loc, inputTypes[3], rank);
670 mlir::Value corankValue =
671 builder.createIntegerConstant(loc, inputTypes[4], corank);
672 args.push_back(categoryValue);
673 args.push_back(kindValue);
674 args.push_back(rankValue);
675 args.push_back(corankValue);
676 builder.create<fir::CallOp>(loc, callee, args);
677 }
678
679 /// Generate call to the AllocatableInitDerived to set up the type descriptor
680 /// and other part of the descriptor for derived type.
681 void genSetType(const Allocation &alloc, const fir::MutableBoxValue &box,
682 mlir::Location loc) {
683 const Fortran::semantics::DeclTypeSpec *typeSpec =
684 getIfAllocateStmtTypeSpec();
685
686 // No type spec provided in allocate statement so the declared type spec is
687 // used.
688 if (!typeSpec)
689 typeSpec = &alloc.type;
690 assert(typeSpec && "type spec missing for polymorphic allocation");
691
692 // Set up the descriptor for allocation for intrinsic type spec on
693 // unlimited polymorphic entity.
694 if (typeSpec->AsIntrinsic() &&
695 fir::isUnlimitedPolymorphicType(fir::getBase(box).getType())) {
696 if (typeSpec->AsIntrinsic()->category() == TypeCategory::Character) {
697 genRuntimeInitCharacter(
698 builder, loc, box, lenParams[0],
699 Fortran::evaluate::ToInt64(typeSpec->AsIntrinsic()->kind())
700 .value());
701 } else {
702 genInitIntrinsic(
703 box, typeSpec->AsIntrinsic()->category(),
704 Fortran::evaluate::ToInt64(typeSpec->AsIntrinsic()->kind()).value(),
705 alloc.getSymbol().Rank());
706 }
707 return;
708 }
709
710 // Do not generate calls for non derived-type type spec.
711 if (!typeSpec->AsDerived())
712 return;
713
714 auto typeDescAddr = Fortran::lower::getTypeDescAddr(
715 converter, loc, typeSpec->derivedTypeSpec());
716 genInitDerived(box, typeDescAddr, alloc.getSymbol().Rank());
717 }
718
719 /// Returns a pointer to the DeclTypeSpec if a type-spec is provided in the
720 /// allocate statement. Returns a null pointer otherwise.
721 const Fortran::semantics::DeclTypeSpec *getIfAllocateStmtTypeSpec() const {
722 if (const auto &typeSpec =
723 std::get<std::optional<Fortran::parser::TypeSpec>>(stmt.t))
724 return typeSpec->declTypeSpec;
725 return nullptr;
726 }
727
728 mlir::Value genCudaAllocate(fir::FirOpBuilder &builder, mlir::Location loc,
729 const fir::MutableBoxValue &box,
730 ErrorManager &errorManager,
731 const Fortran::semantics::Symbol &sym) {
732 Fortran::lower::StatementContext stmtCtx;
733 cuf::DataAttributeAttr cudaAttr =
734 Fortran::lower::translateSymbolCUFDataAttribute(builder.getContext(),
735 sym);
736 mlir::Value errmsg = errMsgExpr ? errorManager.errMsgAddr : nullptr;
737 mlir::Value stream =
738 streamExpr
739 ? fir::getBase(converter.genExprValue(loc, *streamExpr, stmtCtx))
740 : nullptr;
741 mlir::Value pinned =
742 pinnedExpr
743 ? fir::getBase(converter.genExprAddr(loc, *pinnedExpr, stmtCtx))
744 : nullptr;
745 mlir::Value source = sourceExpr ? fir::getBase(sourceExv) : nullptr;
746
747 // Keep return type the same as a standard AllocatableAllocate call.
748 mlir::Type retTy = fir::runtime::getModel<int>()(builder.getContext());
749 return builder
750 .create<cuf::AllocateOp>(
751 loc, retTy, box.getAddr(), errmsg, stream, pinned, source, cudaAttr,
752 errorManager.hasStatSpec() ? builder.getUnitAttr() : nullptr)
753 .getResult();
754 }
755
756 Fortran::lower::AbstractConverter &converter;
757 fir::FirOpBuilder &builder;
758 const Fortran::parser::AllocateStmt &stmt;
759 const Fortran::lower::SomeExpr *sourceExpr{nullptr};
760 const Fortran::lower::SomeExpr *moldExpr{nullptr};
761 const Fortran::lower::SomeExpr *statExpr{nullptr};
762 const Fortran::lower::SomeExpr *errMsgExpr{nullptr};
763 const Fortran::lower::SomeExpr *pinnedExpr{nullptr};
764 const Fortran::lower::SomeExpr *streamExpr{nullptr};
765 // If the allocate has a type spec, lenParams contains the
766 // value of the length parameters that were specified inside.
767 llvm::SmallVector<mlir::Value> lenParams;
768 ErrorManager errorManager;
769 // 9.7.1.2(7) The source-expr is evaluated exactly once for each AllocateStmt.
770 fir::ExtendedValue sourceExv;
771 fir::ExtendedValue moldExv;
772
773 mlir::Location loc;
774 };
775 } // namespace
776
777 void Fortran::lower::genAllocateStmt(
778 Fortran::lower::AbstractConverter &converter,
779 const Fortran::parser::AllocateStmt &stmt, mlir::Location loc) {
780 AllocateStmtHelper{converter, stmt, loc}.lower();
781 }
782
783 //===----------------------------------------------------------------------===//
784 // Deallocate statement implementation
785 //===----------------------------------------------------------------------===//
786
787 static void preDeallocationAction(Fortran::lower::AbstractConverter &converter,
788 fir::FirOpBuilder &builder,
789 mlir::Value beginOpValue,
790 const Fortran::semantics::Symbol &sym) {
791 if (sym.test(Fortran::semantics::Symbol::Flag::AccDeclare))
792 Fortran::lower::attachDeclarePreDeallocAction(converter, builder,
793 beginOpValue, sym);
794 }
795
796 static void postDeallocationAction(Fortran::lower::AbstractConverter &converter,
797 fir::FirOpBuilder &builder,
798 const Fortran::semantics::Symbol &sym) {
799 if (sym.test(Fortran::semantics::Symbol::Flag::AccDeclare))
800 Fortran::lower::attachDeclarePostDeallocAction(converter, builder, sym);
801 }
802
803 static mlir::Value genCudaDeallocate(fir::FirOpBuilder &builder,
804 mlir::Location loc,
805 const fir::MutableBoxValue &box,
806 ErrorManager &errorManager,
807 const Fortran::semantics::Symbol &sym) {
808 cuf::DataAttributeAttr cudaAttr =
809 Fortran::lower::translateSymbolCUFDataAttribute(builder.getContext(),
810 sym);
811 mlir::Value errmsg =
812 mlir::isa<fir::AbsentOp>(errorManager.errMsgAddr.getDefiningOp())
813 ? nullptr
814 : errorManager.errMsgAddr;
815
816 // Keep return type the same as a standard AllocatableAllocate call.
817 mlir::Type retTy = fir::runtime::getModel<int>()(builder.getContext());
818 return builder
819 .create<cuf::DeallocateOp>(
820 loc, retTy, box.getAddr(), errmsg, cudaAttr,
821 errorManager.hasStatSpec() ? builder.getUnitAttr() : nullptr)
822 .getResult();
823 }
824
825 // Generate deallocation of a pointer/allocatable.
826 static mlir::Value
827 genDeallocate(fir::FirOpBuilder &builder,
828 Fortran::lower::AbstractConverter &converter, mlir::Location loc,
829 const fir::MutableBoxValue &box, ErrorManager &errorManager,
830 mlir::Value declaredTypeDesc = {},
831 const Fortran::semantics::Symbol *symbol = nullptr) {
832 bool isCudaSymbol = symbol && Fortran::semantics::HasCUDAAttr(*symbol);
833 // Deallocate intrinsic types inline.
834 if (!box.isDerived() && !box.isPolymorphic() && !box.hasAssumedRank() &&
835 !box.isUnlimitedPolymorphic() && !errorManager.hasStatSpec() &&
836 !useAllocateRuntime && !box.isPointer() && !isCudaSymbol) {
837 // Pointers must use PointerDeallocate so that their deallocations
838 // can be validated.
839 mlir::Value ret = fir::factory::genFreemem(builder, loc, box);
840 if (symbol)
841 postDeallocationAction(converter, builder, *symbol);
842 return ret;
843 }
844 // Use runtime calls to deallocate descriptor cases. Sync MutableBoxValue
845 // with its descriptor before and after calls if needed.
846 errorManager.genStatCheck(builder, loc);
847 mlir::Value stat;
848 if (!isCudaSymbol)
849 stat =
850 genRuntimeDeallocate(builder, loc, box, errorManager, declaredTypeDesc);
851 else
852 stat = genCudaDeallocate(builder, loc, box, errorManager, *symbol);
853 fir::factory::syncMutableBoxFromIRBox(builder, loc, box);
854 if (symbol)
855 postDeallocationAction(converter, builder, *symbol);
856 errorManager.assignStat(builder, loc, stat);
857 return stat;
858 }
859
860 void Fortran::lower::genDeallocateBox(
861 Fortran::lower::AbstractConverter &converter,
862 const fir::MutableBoxValue &box, mlir::Location loc,
863 const Fortran::semantics::Symbol *sym, mlir::Value declaredTypeDesc) {
864 const Fortran::lower::SomeExpr *statExpr = nullptr;
865 const Fortran::lower::SomeExpr *errMsgExpr = nullptr;
866 ErrorManager errorManager;
867 errorManager.init(converter, loc, statExpr, errMsgExpr);
868 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
869 genDeallocate(builder, converter, loc, box, errorManager, declaredTypeDesc,
870 sym);
871 }
872
873 void Fortran::lower::genDeallocateIfAllocated(
874 Fortran::lower::AbstractConverter &converter,
875 const fir::MutableBoxValue &box, mlir::Location loc,
876 const Fortran::semantics::Symbol *sym) {
877 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
878 mlir::Value isAllocated =
879 fir::factory::genIsAllocatedOrAssociatedTest(builder, loc, box);
880 builder.genIfThen(loc, isAllocated)
881 .genThen([&]() {
882 if (mlir::Type eleType = box.getEleTy();
883 mlir::isa<fir::RecordType>(eleType) && box.isPolymorphic()) {
884 mlir::Value declaredTypeDesc = builder.create<fir::TypeDescOp>(
885 loc, mlir::TypeAttr::get(eleType));
886 genDeallocateBox(converter, box, loc, sym, declaredTypeDesc);
887 } else {
888 genDeallocateBox(converter, box, loc, sym);
889 }
890 })
891 .end();
892 }
893
894 void Fortran::lower::genDeallocateStmt(
895 Fortran::lower::AbstractConverter &converter,
896 const Fortran::parser::DeallocateStmt &stmt, mlir::Location loc) {
897 const Fortran::lower::SomeExpr *statExpr = nullptr;
898 const Fortran::lower::SomeExpr *errMsgExpr = nullptr;
899 for (const Fortran::parser::StatOrErrmsg &statOrErr :
900 std::get<std::list<Fortran::parser::StatOrErrmsg>>(stmt.t))
901 Fortran::common::visit(
902 Fortran::common::visitors{
903 [&](const Fortran::parser::StatVariable &statVar) {
904 statExpr = Fortran::semantics::GetExpr(statVar);
905 },
906 [&](const Fortran::parser::MsgVariable &errMsgVar) {
907 errMsgExpr = Fortran::semantics::GetExpr(errMsgVar);
908 },
909 },
910 statOrErr.u);
911 ErrorManager errorManager;
912 errorManager.init(converter, loc, statExpr, errMsgExpr);
913 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
914 mlir::OpBuilder::InsertPoint insertPt = builder.saveInsertionPoint();
915 for (const Fortran::parser::AllocateObject &allocateObject :
916 std::get<std::list<Fortran::parser::AllocateObject>>(stmt.t)) {
917 const Fortran::semantics::Symbol &symbol = unwrapSymbol(allocateObject);
918 fir::MutableBoxValue box =
919 genMutableBoxValue(converter, loc, allocateObject);
920 mlir::Value declaredTypeDesc = {};
921 if (box.isPolymorphic()) {
922 mlir::Type eleType = box.getEleTy();
923 if (mlir::isa<fir::RecordType>(eleType))
924 if (const Fortran::semantics::DerivedTypeSpec *derivedTypeSpec =
925 symbol.GetType()->AsDerived()) {
926 declaredTypeDesc =
927 Fortran::lower::getTypeDescAddr(converter, loc, *derivedTypeSpec);
928 }
929 }
930 mlir::Value beginOpValue = genDeallocate(
931 builder, converter, loc, box, errorManager, declaredTypeDesc, &symbol);
932 preDeallocationAction(converter, builder, beginOpValue, symbol);
933 }
934 builder.restoreInsertionPoint(insertPt);
935 }
936
937 //===----------------------------------------------------------------------===//
938 // MutableBoxValue creation implementation
939 //===----------------------------------------------------------------------===//
940
941 /// Is this symbol a pointer to a pointer array that does not have the
942 /// CONTIGUOUS attribute ?
943 static inline bool
944 isNonContiguousArrayPointer(const Fortran::semantics::Symbol &sym) {
945 return Fortran::semantics::IsPointer(sym) && sym.Rank() != 0 &&
946 !sym.attrs().test(Fortran::semantics::Attr::CONTIGUOUS);
947 }
948
949 /// Is this symbol a polymorphic pointer?
950 static inline bool isPolymorphicPointer(const Fortran::semantics::Symbol &sym) {
951 return Fortran::semantics::IsPointer(sym) &&
952 Fortran::semantics::IsPolymorphic(sym);
953 }
954
955 /// Is this symbol a polymorphic allocatable?
956 static inline bool
957 isPolymorphicAllocatable(const Fortran::semantics::Symbol &sym) {
958 return Fortran::semantics::IsAllocatable(sym) &&
959 Fortran::semantics::IsPolymorphic(sym);
960 }
961
962 /// Is this a local procedure symbol in a procedure that contains internal
963 /// procedures ?
964 static bool mayBeCapturedInInternalProc(const Fortran::semantics::Symbol &sym) {
965 const Fortran::semantics::Scope &owner = sym.owner();
966 Fortran::semantics::Scope::Kind kind = owner.kind();
967 // Test if this is a procedure scope that contains a subprogram scope that is
968 // not an interface.
969 if (kind == Fortran::semantics::Scope::Kind::Subprogram ||
970 kind == Fortran::semantics::Scope::Kind::MainProgram)
971 for (const Fortran::semantics::Scope &childScope : owner.children())
972 if (childScope.kind() == Fortran::semantics::Scope::Kind::Subprogram)
973 if (const Fortran::semantics::Symbol *childSym = childScope.symbol())
974 if (const auto *details =
975 childSym->detailsIf<Fortran::semantics::SubprogramDetails>())
976 if (!details->isInterface())
977 return true;
978 return false;
979 }
980
981 /// In case it is safe to track the properties in variables outside a
982 /// descriptor, create the variables to hold the mutable properties of the
983 /// entity var. The variables are not initialized here.
984 static fir::MutableProperties
985 createMutableProperties(Fortran::lower::AbstractConverter &converter,
986 mlir::Location loc,
987 const Fortran::lower::pft::Variable &var,
988 mlir::ValueRange nonDeferredParams, bool alwaysUseBox) {
989 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
990 const Fortran::semantics::Symbol &sym = var.getSymbol();
991 // Globals and dummies may be associated, creating local variables would
992 // require keeping the values and descriptor before and after every single
993 // impure calls in the current scope (not only the ones taking the variable as
994 // arguments. All.) Volatile means the variable may change in ways not defined
995 // per Fortran, so lowering can most likely not keep the descriptor and values
996 // in sync as needed.
997 // Pointers to non contiguous arrays need to be represented with a fir.box to
998 // account for the discontiguity.
999 // Pointer/Allocatable in internal procedure are descriptors in the host link,
1000 // and it would increase complexity to sync this descriptor with the local
1001 // values every time the host link is escaping.
1002 if (alwaysUseBox || var.isGlobal() || Fortran::semantics::IsDummy(sym) ||
1003 Fortran::semantics::IsFunctionResult(sym) ||
1004 sym.attrs().test(Fortran::semantics::Attr::VOLATILE) ||
1005 isNonContiguousArrayPointer(sym) || useAllocateRuntime ||
1006 useDescForMutableBox || mayBeCapturedInInternalProc(sym) ||
1007 isPolymorphicPointer(sym) || isPolymorphicAllocatable(sym))
1008 return {};
1009 fir::MutableProperties mutableProperties;
1010 std::string name = converter.mangleName(sym);
1011 mlir::Type baseAddrTy = converter.genType(sym);
1012 if (auto boxType = mlir::dyn_cast<fir::BaseBoxType>(baseAddrTy))
1013 baseAddrTy = boxType.getEleTy();
1014 // Allocate and set a variable to hold the address.
1015 // It will be set to null in setUnallocatedStatus.
1016 mutableProperties.addr = builder.allocateLocal(
1017 loc, baseAddrTy, name + ".addr", "",
1018 /*shape=*/std::nullopt, /*typeparams=*/std::nullopt);
1019 // Allocate variables to hold lower bounds and extents.
1020 int rank = sym.Rank();
1021 mlir::Type idxTy = builder.getIndexType();
1022 for (decltype(rank) i = 0; i < rank; ++i) {
1023 mlir::Value lboundVar = builder.allocateLocal(
1024 loc, idxTy, name + ".lb" + std::to_string(i), "",
1025 /*shape=*/std::nullopt, /*typeparams=*/std::nullopt);
1026 mlir::Value extentVar = builder.allocateLocal(
1027 loc, idxTy, name + ".ext" + std::to_string(i), "",
1028 /*shape=*/std::nullopt, /*typeparams=*/std::nullopt);
1029 mutableProperties.lbounds.emplace_back(lboundVar);
1030 mutableProperties.extents.emplace_back(extentVar);
1031 }
1032
1033 // Allocate variable to hold deferred length parameters.
1034 mlir::Type eleTy = baseAddrTy;
1035 if (auto newTy = fir::dyn_cast_ptrEleTy(eleTy))
1036 eleTy = newTy;
1037 if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(eleTy))
1038 eleTy = seqTy.getEleTy();
1039 if (auto record = mlir::dyn_cast<fir::RecordType>(eleTy))
1040 if (record.getNumLenParams() != 0)
1041 TODO(loc, "deferred length type parameters.");
1042 if (fir::isa_char(eleTy) && nonDeferredParams.empty()) {
1043 mlir::Value lenVar =
1044 builder.allocateLocal(loc, builder.getCharacterLengthType(),
1045 name + ".len", "", /*shape=*/std::nullopt,
1046 /*typeparams=*/std::nullopt);
1047 mutableProperties.deferredParams.emplace_back(lenVar);
1048 }
1049 return mutableProperties;
1050 }
1051
1052 fir::MutableBoxValue Fortran::lower::createMutableBox(
1053 Fortran::lower::AbstractConverter &converter, mlir::Location loc,
1054 const Fortran::lower::pft::Variable &var, mlir::Value boxAddr,
1055 mlir::ValueRange nonDeferredParams, bool alwaysUseBox) {
1056
1057 fir::MutableProperties mutableProperties = createMutableProperties(
1058 converter, loc, var, nonDeferredParams, alwaysUseBox);
1059 fir::MutableBoxValue box(boxAddr, nonDeferredParams, mutableProperties);
1060 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
1061 if (!var.isGlobal() && !Fortran::semantics::IsDummy(var.getSymbol()))
1062 fir::factory::disassociateMutableBox(builder, loc, box,
1063 /*polymorphicSetType=*/false);
1064 return box;
1065 }
1066
1067 //===----------------------------------------------------------------------===//
1068 // MutableBoxValue reading interface implementation
1069 //===----------------------------------------------------------------------===//
1070
1071 bool Fortran::lower::isArraySectionWithoutVectorSubscript(
1072 const Fortran::lower::SomeExpr &expr) {
1073 return expr.Rank() > 0 && Fortran::evaluate::IsVariable(expr) &&
1074 !Fortran::evaluate::UnwrapWholeSymbolDataRef(expr) &&
1075 !Fortran::evaluate::HasVectorSubscript(expr);
1076 }
1077
1078 void Fortran::lower::associateMutableBox(
1079 Fortran::lower::AbstractConverter &converter, mlir::Location loc,
1080 const fir::MutableBoxValue &box, const Fortran::lower::SomeExpr &source,
1081 mlir::ValueRange lbounds, Fortran::lower::StatementContext &stmtCtx) {
1082 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
1083 if (Fortran::evaluate::UnwrapExpr<Fortran::evaluate::NullPointer>(source)) {
1084 fir::factory::disassociateMutableBox(builder, loc, box);
1085 return;
1086 }
1087 if (converter.getLoweringOptions().getLowerToHighLevelFIR()) {
1088 fir::ExtendedValue rhs = converter.genExprAddr(loc, source, stmtCtx);
1089 fir::factory::associateMutableBox(builder, loc, box, rhs, lbounds);
1090 return;
1091 }
1092 // The right hand side is not be evaluated into a temp. Array sections can
1093 // typically be represented as a value of type `!fir.box`. However, an
1094 // expression that uses vector subscripts cannot be emboxed. In that case,
1095 // generate a reference to avoid having to later use a fir.rebox to implement
1096 // the pointer association.
1097 fir::ExtendedValue rhs = isArraySectionWithoutVectorSubscript(source)
1098 ? converter.genExprBox(loc, source, stmtCtx)
1099 : converter.genExprAddr(loc, source, stmtCtx);
1100
1101 fir::factory::associateMutableBox(builder, loc, box, rhs, lbounds);
1102 }
1103
1104 bool Fortran::lower::isWholeAllocatable(const Fortran::lower::SomeExpr &expr) {
1105 if (const Fortran::semantics::Symbol *sym =
1106 Fortran::evaluate::UnwrapWholeSymbolOrComponentDataRef(expr))
1107 return Fortran::semantics::IsAllocatable(sym->GetUltimate());
1108 return false;
1109 }
1110
1111 bool Fortran::lower::isWholePointer(const Fortran::lower::SomeExpr &expr) {
1112 if (const Fortran::semantics::Symbol *sym =
1113 Fortran::evaluate::UnwrapWholeSymbolOrComponentDataRef(expr))
1114 return Fortran::semantics::IsPointer(sym->GetUltimate());
1115 return false;
1116 }
1117
1118 mlir::Value Fortran::lower::getAssumedCharAllocatableOrPointerLen(
1119 fir::FirOpBuilder &builder, mlir::Location loc,
1120 const Fortran::semantics::Symbol &sym, mlir::Value box) {
1121 // Read length from fir.box (explicit expr cannot safely be re-evaluated
1122 // here).
1123 auto readLength = [&]() {
1124 fir::BoxValue boxLoad =
1125 builder.create<fir::LoadOp>(loc, fir::getBase(box)).getResult();
1126 return fir::factory::readCharLen(builder, loc, boxLoad);
1127 };
1128 if (Fortran::semantics::IsOptional(sym)) {
1129 mlir::IndexType idxTy = builder.getIndexType();
1130 // It is not safe to unconditionally read boxes of optionals in case
1131 // they are absents. According to 15.5.2.12 3 (9), it is illegal to
1132 // inquire the length of absent optional, even if non deferred, so
1133 // it's fine to use undefOp in this case.
1134 auto isPresent = builder.create<fir::IsPresentOp>(loc, builder.getI1Type(),
1135 fir::getBase(box));
1136 mlir::Value len =
1137 builder.genIfOp(loc, {idxTy}, isPresent, true)
1138 .genThen(
1139 [&]() { builder.create<fir::ResultOp>(loc, readLength()); })
1140 .genElse([&]() {
1141 auto undef = builder.create<fir::UndefOp>(loc, idxTy);
1142 builder.create<fir::ResultOp>(loc, undef.getResult());
1143 })
1144 .getResults()[0];
1145 return len;
1146 }
1147
1148 return readLength();
1149 }
1150
1151 mlir::Value Fortran::lower::getTypeDescAddr(
1152 AbstractConverter &converter, mlir::Location loc,
1153 const Fortran::semantics::DerivedTypeSpec &typeSpec) {
1154 mlir::Type typeDesc =
1155 Fortran::lower::translateDerivedTypeToFIRType(converter, typeSpec);
1156 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
1157 return builder.create<fir::TypeDescOp>(loc, mlir::TypeAttr::get(typeDesc));
1158 }