1aab4263aSValentin Clement //===-- Runtime.cpp -------------------------------------------------------===//
2aab4263aSValentin Clement //
3aab4263aSValentin Clement // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4aab4263aSValentin Clement // See https://llvm.org/LICENSE.txt for license information.
5aab4263aSValentin Clement // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6aab4263aSValentin Clement //
7aab4263aSValentin Clement //===----------------------------------------------------------------------===//
8aab4263aSValentin Clement 
9aab4263aSValentin Clement #include "flang/Lower/Runtime.h"
10aab4263aSValentin Clement #include "flang/Lower/Bridge.h"
11d0b70a07SValentin Clement #include "flang/Lower/StatementContext.h"
12aab4263aSValentin Clement #include "flang/Lower/Todo.h"
13aab4263aSValentin Clement #include "flang/Optimizer/Builder/FIRBuilder.h"
14aab4263aSValentin Clement #include "flang/Optimizer/Builder/Runtime/RTBuilder.h"
15aab4263aSValentin Clement #include "flang/Parser/parse-tree.h"
16a16eddb2SValentin Clement #include "flang/Runtime/misc-intrinsic.h"
1772276bdaSValentin Clement #include "flang/Runtime/pointer.h"
18a1918fdfSValentin Clement #include "flang/Runtime/random.h"
19aab4263aSValentin Clement #include "flang/Runtime/stop.h"
209daf5765SValentin Clement #include "flang/Runtime/time-intrinsic.h"
21aab4263aSValentin Clement #include "flang/Semantics/tools.h"
22aab4263aSValentin Clement #include "llvm/Support/Debug.h"
23aab4263aSValentin Clement 
24aab4263aSValentin Clement #define DEBUG_TYPE "flang-lower-runtime"
25aab4263aSValentin Clement 
26aab4263aSValentin Clement using namespace Fortran::runtime;
27aab4263aSValentin Clement 
28aab4263aSValentin Clement /// Runtime calls that do not return to the caller indicate this condition by
29aab4263aSValentin Clement /// terminating the current basic block with an unreachable op.
30aab4263aSValentin Clement static void genUnreachable(fir::FirOpBuilder &builder, mlir::Location loc) {
31aab4263aSValentin Clement   builder.create<fir::UnreachableOp>(loc);
32aab4263aSValentin Clement   mlir::Block *newBlock =
33aab4263aSValentin Clement       builder.getBlock()->splitBlock(builder.getInsertionPoint());
34aab4263aSValentin Clement   builder.setInsertionPointToStart(newBlock);
35aab4263aSValentin Clement }
36aab4263aSValentin Clement 
37aab4263aSValentin Clement //===----------------------------------------------------------------------===//
38aab4263aSValentin Clement // Misc. Fortran statements that lower to runtime calls
39aab4263aSValentin Clement //===----------------------------------------------------------------------===//
40aab4263aSValentin Clement 
41aab4263aSValentin Clement void Fortran::lower::genStopStatement(
42aab4263aSValentin Clement     Fortran::lower::AbstractConverter &converter,
43aab4263aSValentin Clement     const Fortran::parser::StopStmt &stmt) {
44aab4263aSValentin Clement   fir::FirOpBuilder &builder = converter.getFirOpBuilder();
45aab4263aSValentin Clement   mlir::Location loc = converter.getCurrentLocation();
46d0b70a07SValentin Clement   Fortran::lower::StatementContext stmtCtx;
47aab4263aSValentin Clement   llvm::SmallVector<mlir::Value> operands;
48aab4263aSValentin Clement   mlir::FuncOp callee;
49aab4263aSValentin Clement   mlir::FunctionType calleeType;
50aab4263aSValentin Clement   // First operand is stop code (zero if absent)
51ca53e049SValentin Clement   if (const auto &code =
52ca53e049SValentin Clement           std::get<std::optional<Fortran::parser::StopCode>>(stmt.t)) {
53d0b70a07SValentin Clement     auto expr =
54d0b70a07SValentin Clement         converter.genExprValue(*Fortran::semantics::GetExpr(*code), stmtCtx);
55ca53e049SValentin Clement     LLVM_DEBUG(llvm::dbgs() << "stop expression: "; expr.dump();
56ca53e049SValentin Clement                llvm::dbgs() << '\n');
57ca53e049SValentin Clement     expr.match(
58ca53e049SValentin Clement         [&](const fir::CharBoxValue &x) {
59a8d48fe0SValentin Clement           callee = fir::runtime::getRuntimeFunc<mkRTKey(StopStatementText)>(
60a8d48fe0SValentin Clement               loc, builder);
61*4a3460a7SRiver Riddle           calleeType = callee.getFunctionType();
62a8d48fe0SValentin Clement           // Creates a pair of operands for the CHARACTER and its LEN.
63a8d48fe0SValentin Clement           operands.push_back(
64a8d48fe0SValentin Clement               builder.createConvert(loc, calleeType.getInput(0), x.getAddr()));
65a8d48fe0SValentin Clement           operands.push_back(
66a8d48fe0SValentin Clement               builder.createConvert(loc, calleeType.getInput(1), x.getLen()));
67ca53e049SValentin Clement         },
68ca53e049SValentin Clement         [&](fir::UnboxedValue x) {
69ca53e049SValentin Clement           callee = fir::runtime::getRuntimeFunc<mkRTKey(StopStatement)>(
70ca53e049SValentin Clement               loc, builder);
71*4a3460a7SRiver Riddle           calleeType = callee.getFunctionType();
72ca53e049SValentin Clement           mlir::Value cast =
73ca53e049SValentin Clement               builder.createConvert(loc, calleeType.getInput(0), x);
74ca53e049SValentin Clement           operands.push_back(cast);
75ca53e049SValentin Clement         },
76ca53e049SValentin Clement         [&](auto) {
77ca53e049SValentin Clement           mlir::emitError(loc, "unhandled expression in STOP");
78ca53e049SValentin Clement           std::exit(1);
79ca53e049SValentin Clement         });
80aab4263aSValentin Clement   } else {
81aab4263aSValentin Clement     callee = fir::runtime::getRuntimeFunc<mkRTKey(StopStatement)>(loc, builder);
82*4a3460a7SRiver Riddle     calleeType = callee.getFunctionType();
83aab4263aSValentin Clement     operands.push_back(
84aab4263aSValentin Clement         builder.createIntegerConstant(loc, calleeType.getInput(0), 0));
85aab4263aSValentin Clement   }
86aab4263aSValentin Clement 
87aab4263aSValentin Clement   // Second operand indicates ERROR STOP
88aab4263aSValentin Clement   bool isError = std::get<Fortran::parser::StopStmt::Kind>(stmt.t) ==
89aab4263aSValentin Clement                  Fortran::parser::StopStmt::Kind::ErrorStop;
90aab4263aSValentin Clement   operands.push_back(builder.createIntegerConstant(
91aab4263aSValentin Clement       loc, calleeType.getInput(operands.size()), isError));
92aab4263aSValentin Clement 
93aab4263aSValentin Clement   // Third operand indicates QUIET (default to false).
94cc306740SValentin Clement   if (const auto &quiet =
95cc306740SValentin Clement           std::get<std::optional<Fortran::parser::ScalarLogicalExpr>>(stmt.t)) {
96cc306740SValentin Clement     const SomeExpr *expr = Fortran::semantics::GetExpr(*quiet);
97cc306740SValentin Clement     assert(expr && "failed getting typed expression");
98d0b70a07SValentin Clement     mlir::Value q = fir::getBase(converter.genExprValue(*expr, stmtCtx));
99cc306740SValentin Clement     operands.push_back(
100cc306740SValentin Clement         builder.createConvert(loc, calleeType.getInput(operands.size()), q));
101aab4263aSValentin Clement   } else {
102aab4263aSValentin Clement     operands.push_back(builder.createIntegerConstant(
103aab4263aSValentin Clement         loc, calleeType.getInput(operands.size()), 0));
104aab4263aSValentin Clement   }
105aab4263aSValentin Clement 
106aab4263aSValentin Clement   builder.create<fir::CallOp>(loc, callee, operands);
107aab4263aSValentin Clement   genUnreachable(builder, loc);
108aab4263aSValentin Clement }
109db01b123SValentin Clement 
110db01b123SValentin Clement void Fortran::lower::genPauseStatement(
111db01b123SValentin Clement     Fortran::lower::AbstractConverter &converter,
112db01b123SValentin Clement     const Fortran::parser::PauseStmt &) {
113db01b123SValentin Clement   fir::FirOpBuilder &builder = converter.getFirOpBuilder();
114db01b123SValentin Clement   mlir::Location loc = converter.getCurrentLocation();
115db01b123SValentin Clement   mlir::FuncOp callee =
116db01b123SValentin Clement       fir::runtime::getRuntimeFunc<mkRTKey(PauseStatement)>(loc, builder);
117db01b123SValentin Clement   builder.create<fir::CallOp>(loc, callee, llvm::None);
118db01b123SValentin Clement }
11972276bdaSValentin Clement 
12072276bdaSValentin Clement mlir::Value Fortran::lower::genAssociated(fir::FirOpBuilder &builder,
12172276bdaSValentin Clement                                           mlir::Location loc,
12272276bdaSValentin Clement                                           mlir::Value pointer,
12372276bdaSValentin Clement                                           mlir::Value target) {
12472276bdaSValentin Clement   mlir::FuncOp func =
12572276bdaSValentin Clement       fir::runtime::getRuntimeFunc<mkRTKey(PointerIsAssociatedWith)>(loc,
12672276bdaSValentin Clement                                                                      builder);
12772276bdaSValentin Clement   llvm::SmallVector<mlir::Value> args = fir::runtime::createArguments(
128*4a3460a7SRiver Riddle       builder, loc, func.getFunctionType(), pointer, target);
12972276bdaSValentin Clement   return builder.create<fir::CallOp>(loc, func, args).getResult(0);
13072276bdaSValentin Clement }
131a1918fdfSValentin Clement 
1329daf5765SValentin Clement mlir::Value Fortran::lower::genCpuTime(fir::FirOpBuilder &builder,
1339daf5765SValentin Clement                                        mlir::Location loc) {
1349daf5765SValentin Clement   mlir::FuncOp func =
1359daf5765SValentin Clement       fir::runtime::getRuntimeFunc<mkRTKey(CpuTime)>(loc, builder);
1369daf5765SValentin Clement   return builder.create<fir::CallOp>(loc, func, llvm::None).getResult(0);
1379daf5765SValentin Clement }
1389daf5765SValentin Clement 
1399daf5765SValentin Clement void Fortran::lower::genDateAndTime(fir::FirOpBuilder &builder,
1409daf5765SValentin Clement                                     mlir::Location loc,
1419daf5765SValentin Clement                                     llvm::Optional<fir::CharBoxValue> date,
1429daf5765SValentin Clement                                     llvm::Optional<fir::CharBoxValue> time,
1439daf5765SValentin Clement                                     llvm::Optional<fir::CharBoxValue> zone,
1449daf5765SValentin Clement                                     mlir::Value values) {
1459daf5765SValentin Clement   mlir::FuncOp callee =
1469daf5765SValentin Clement       fir::runtime::getRuntimeFunc<mkRTKey(DateAndTime)>(loc, builder);
147*4a3460a7SRiver Riddle   mlir::FunctionType funcTy = callee.getFunctionType();
1489daf5765SValentin Clement   mlir::Type idxTy = builder.getIndexType();
1499daf5765SValentin Clement   mlir::Value zero;
1509daf5765SValentin Clement   auto splitArg = [&](llvm::Optional<fir::CharBoxValue> arg,
1519daf5765SValentin Clement                       mlir::Value &buffer, mlir::Value &len) {
1529daf5765SValentin Clement     if (arg) {
1539daf5765SValentin Clement       buffer = arg->getBuffer();
1549daf5765SValentin Clement       len = arg->getLen();
1559daf5765SValentin Clement     } else {
1569daf5765SValentin Clement       if (!zero)
1579daf5765SValentin Clement         zero = builder.createIntegerConstant(loc, idxTy, 0);
1589daf5765SValentin Clement       buffer = zero;
1599daf5765SValentin Clement       len = zero;
1609daf5765SValentin Clement     }
1619daf5765SValentin Clement   };
1629daf5765SValentin Clement   mlir::Value dateBuffer;
1639daf5765SValentin Clement   mlir::Value dateLen;
1649daf5765SValentin Clement   splitArg(date, dateBuffer, dateLen);
1659daf5765SValentin Clement   mlir::Value timeBuffer;
1669daf5765SValentin Clement   mlir::Value timeLen;
1679daf5765SValentin Clement   splitArg(time, timeBuffer, timeLen);
1689daf5765SValentin Clement   mlir::Value zoneBuffer;
1699daf5765SValentin Clement   mlir::Value zoneLen;
1709daf5765SValentin Clement   splitArg(zone, zoneBuffer, zoneLen);
1719daf5765SValentin Clement 
1729daf5765SValentin Clement   mlir::Value sourceFile = fir::factory::locationToFilename(builder, loc);
1739daf5765SValentin Clement   mlir::Value sourceLine =
1749daf5765SValentin Clement       fir::factory::locationToLineNo(builder, loc, funcTy.getInput(7));
1759daf5765SValentin Clement 
1769daf5765SValentin Clement   llvm::SmallVector<mlir::Value> args = fir::runtime::createArguments(
1779daf5765SValentin Clement       builder, loc, funcTy, dateBuffer, dateLen, timeBuffer, timeLen,
1789daf5765SValentin Clement       zoneBuffer, zoneLen, sourceFile, sourceLine, values);
1799daf5765SValentin Clement   builder.create<fir::CallOp>(loc, callee, args);
1809daf5765SValentin Clement }
1819daf5765SValentin Clement 
182a1918fdfSValentin Clement void Fortran::lower::genRandomInit(fir::FirOpBuilder &builder,
183a1918fdfSValentin Clement                                    mlir::Location loc, mlir::Value repeatable,
184a1918fdfSValentin Clement                                    mlir::Value imageDistinct) {
185a1918fdfSValentin Clement   mlir::FuncOp func =
186a1918fdfSValentin Clement       fir::runtime::getRuntimeFunc<mkRTKey(RandomInit)>(loc, builder);
187a1918fdfSValentin Clement   llvm::SmallVector<mlir::Value> args = fir::runtime::createArguments(
188*4a3460a7SRiver Riddle       builder, loc, func.getFunctionType(), repeatable, imageDistinct);
189a1918fdfSValentin Clement   builder.create<fir::CallOp>(loc, func, args);
190a1918fdfSValentin Clement }
191a1918fdfSValentin Clement 
192a1918fdfSValentin Clement void Fortran::lower::genRandomNumber(fir::FirOpBuilder &builder,
193a1918fdfSValentin Clement                                      mlir::Location loc, mlir::Value harvest) {
194a1918fdfSValentin Clement   mlir::FuncOp func =
195a1918fdfSValentin Clement       fir::runtime::getRuntimeFunc<mkRTKey(RandomNumber)>(loc, builder);
196*4a3460a7SRiver Riddle   mlir::FunctionType funcTy = func.getFunctionType();
197a1918fdfSValentin Clement   mlir::Value sourceFile = fir::factory::locationToFilename(builder, loc);
198a1918fdfSValentin Clement   mlir::Value sourceLine =
199a1918fdfSValentin Clement       fir::factory::locationToLineNo(builder, loc, funcTy.getInput(2));
200a1918fdfSValentin Clement   llvm::SmallVector<mlir::Value> args = fir::runtime::createArguments(
201a1918fdfSValentin Clement       builder, loc, funcTy, harvest, sourceFile, sourceLine);
202a1918fdfSValentin Clement   builder.create<fir::CallOp>(loc, func, args);
203a1918fdfSValentin Clement }
204a1918fdfSValentin Clement 
205a1918fdfSValentin Clement void Fortran::lower::genRandomSeed(fir::FirOpBuilder &builder,
206a1918fdfSValentin Clement                                    mlir::Location loc, int argIndex,
207a1918fdfSValentin Clement                                    mlir::Value argBox) {
208a1918fdfSValentin Clement   mlir::FuncOp func;
209a1918fdfSValentin Clement   // argIndex is the nth (0-origin) argument in declaration order,
210a1918fdfSValentin Clement   // or -1 if no argument is present.
211a1918fdfSValentin Clement   switch (argIndex) {
212a1918fdfSValentin Clement   case -1:
213a1918fdfSValentin Clement     func = fir::runtime::getRuntimeFunc<mkRTKey(RandomSeedDefaultPut)>(loc,
214a1918fdfSValentin Clement                                                                        builder);
215a1918fdfSValentin Clement     builder.create<fir::CallOp>(loc, func);
216a1918fdfSValentin Clement     return;
217a1918fdfSValentin Clement   case 0:
218a1918fdfSValentin Clement     func = fir::runtime::getRuntimeFunc<mkRTKey(RandomSeedSize)>(loc, builder);
219a1918fdfSValentin Clement     break;
220a1918fdfSValentin Clement   case 1:
221a1918fdfSValentin Clement     func = fir::runtime::getRuntimeFunc<mkRTKey(RandomSeedPut)>(loc, builder);
222a1918fdfSValentin Clement     break;
223a1918fdfSValentin Clement   case 2:
224a1918fdfSValentin Clement     func = fir::runtime::getRuntimeFunc<mkRTKey(RandomSeedGet)>(loc, builder);
225a1918fdfSValentin Clement     break;
226a1918fdfSValentin Clement   default:
227a1918fdfSValentin Clement     llvm::report_fatal_error("invalid RANDOM_SEED argument index");
228a1918fdfSValentin Clement   }
229*4a3460a7SRiver Riddle   mlir::FunctionType funcTy = func.getFunctionType();
230a1918fdfSValentin Clement   mlir::Value sourceFile = fir::factory::locationToFilename(builder, loc);
231a1918fdfSValentin Clement   mlir::Value sourceLine =
232a1918fdfSValentin Clement       fir::factory::locationToLineNo(builder, loc, funcTy.getInput(2));
233a1918fdfSValentin Clement   llvm::SmallVector<mlir::Value> args = fir::runtime::createArguments(
234a1918fdfSValentin Clement       builder, loc, funcTy, argBox, sourceFile, sourceLine);
235a1918fdfSValentin Clement   builder.create<fir::CallOp>(loc, func, args);
236a1918fdfSValentin Clement }
237264d9662SValentin Clement 
238a16eddb2SValentin Clement /// generate runtime call to transfer intrinsic with no size argument
239a16eddb2SValentin Clement void Fortran::lower::genTransfer(fir::FirOpBuilder &builder, mlir::Location loc,
240a16eddb2SValentin Clement                                  mlir::Value resultBox, mlir::Value sourceBox,
241a16eddb2SValentin Clement                                  mlir::Value moldBox) {
242a16eddb2SValentin Clement 
243a16eddb2SValentin Clement   mlir::FuncOp func =
244a16eddb2SValentin Clement       fir::runtime::getRuntimeFunc<mkRTKey(Transfer)>(loc, builder);
245*4a3460a7SRiver Riddle   mlir::FunctionType fTy = func.getFunctionType();
246a16eddb2SValentin Clement   mlir::Value sourceFile = fir::factory::locationToFilename(builder, loc);
247a16eddb2SValentin Clement   mlir::Value sourceLine =
248a16eddb2SValentin Clement       fir::factory::locationToLineNo(builder, loc, fTy.getInput(4));
249a16eddb2SValentin Clement   llvm::SmallVector<mlir::Value> args = fir::runtime::createArguments(
250a16eddb2SValentin Clement       builder, loc, fTy, resultBox, sourceBox, moldBox, sourceFile, sourceLine);
251a16eddb2SValentin Clement   builder.create<fir::CallOp>(loc, func, args);
252a16eddb2SValentin Clement }
253a16eddb2SValentin Clement 
254a16eddb2SValentin Clement /// generate runtime call to transfer intrinsic with size argument
255a16eddb2SValentin Clement void Fortran::lower::genTransferSize(fir::FirOpBuilder &builder,
256a16eddb2SValentin Clement                                      mlir::Location loc, mlir::Value resultBox,
257a16eddb2SValentin Clement                                      mlir::Value sourceBox, mlir::Value moldBox,
258a16eddb2SValentin Clement                                      mlir::Value size) {
259a16eddb2SValentin Clement   mlir::FuncOp func =
260a16eddb2SValentin Clement       fir::runtime::getRuntimeFunc<mkRTKey(TransferSize)>(loc, builder);
261*4a3460a7SRiver Riddle   mlir::FunctionType fTy = func.getFunctionType();
262a16eddb2SValentin Clement   mlir::Value sourceFile = fir::factory::locationToFilename(builder, loc);
263a16eddb2SValentin Clement   mlir::Value sourceLine =
264a16eddb2SValentin Clement       fir::factory::locationToLineNo(builder, loc, fTy.getInput(4));
265a16eddb2SValentin Clement   llvm::SmallVector<mlir::Value> args =
266a16eddb2SValentin Clement       fir::runtime::createArguments(builder, loc, fTy, resultBox, sourceBox,
267a16eddb2SValentin Clement                                     moldBox, sourceFile, sourceLine, size);
268a16eddb2SValentin Clement   builder.create<fir::CallOp>(loc, func, args);
269a16eddb2SValentin Clement }
270a16eddb2SValentin Clement 
271264d9662SValentin Clement /// generate system_clock runtime call/s
272264d9662SValentin Clement /// all intrinsic arguments are optional and may appear here as mlir::Value{}
273264d9662SValentin Clement void Fortran::lower::genSystemClock(fir::FirOpBuilder &builder,
274264d9662SValentin Clement                                     mlir::Location loc, mlir::Value count,
275264d9662SValentin Clement                                     mlir::Value rate, mlir::Value max) {
276264d9662SValentin Clement   auto makeCall = [&](mlir::FuncOp func, mlir::Value arg) {
277*4a3460a7SRiver Riddle     mlir::Type kindTy = func.getFunctionType().getInput(0);
278264d9662SValentin Clement     int integerKind = 8;
279264d9662SValentin Clement     if (auto intType =
280264d9662SValentin Clement             fir::unwrapRefType(arg.getType()).dyn_cast<mlir::IntegerType>())
281264d9662SValentin Clement       integerKind = intType.getWidth() / 8;
282264d9662SValentin Clement     mlir::Value kind = builder.createIntegerConstant(loc, kindTy, integerKind);
283264d9662SValentin Clement     mlir::Value res =
284264d9662SValentin Clement         builder.create<fir::CallOp>(loc, func, mlir::ValueRange{kind})
285264d9662SValentin Clement             .getResult(0);
286264d9662SValentin Clement     mlir::Value castRes =
287264d9662SValentin Clement         builder.createConvert(loc, fir::dyn_cast_ptrEleTy(arg.getType()), res);
288264d9662SValentin Clement     builder.create<fir::StoreOp>(loc, castRes, arg);
289264d9662SValentin Clement   };
290264d9662SValentin Clement   using fir::runtime::getRuntimeFunc;
291264d9662SValentin Clement   if (count)
292264d9662SValentin Clement     makeCall(getRuntimeFunc<mkRTKey(SystemClockCount)>(loc, builder), count);
293264d9662SValentin Clement   if (rate)
294264d9662SValentin Clement     makeCall(getRuntimeFunc<mkRTKey(SystemClockCountRate)>(loc, builder), rate);
295264d9662SValentin Clement   if (max)
296264d9662SValentin Clement     makeCall(getRuntimeFunc<mkRTKey(SystemClockCountMax)>(loc, builder), max);
297264d9662SValentin Clement }
298