IO.cpp
65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
//===-- IO.cpp -- I/O statement lowering ----------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "flang/Lower/IO.h"
#include "../../runtime/io-api.h"
#include "RTBuilder.h"
#include "flang/Lower/Bridge.h"
#include "flang/Lower/CharacterExpr.h"
#include "flang/Lower/ComplexExpr.h"
#include "flang/Lower/FIRBuilder.h"
#include "flang/Lower/PFTBuilder.h"
#include "flang/Lower/Runtime.h"
#include "flang/Lower/Utils.h"
#include "flang/Parser/parse-tree.h"
#include "flang/Semantics/tools.h"
#include "mlir/Dialect/StandardOps/IR/Ops.h"
#define TODO() llvm_unreachable("not yet implemented")
using namespace Fortran::runtime::io;
#define NAMIFY_HELPER(X) #X
#define NAMIFY(X) NAMIFY_HELPER(IONAME(X))
#define mkIOKey(X) mkKey(IONAME(X))
namespace Fortran::lower {
/// Static table of IO runtime calls
///
/// This logical map contains the name and type builder function for each IO
/// runtime function listed in the tuple. This table is fully constructed at
/// compile-time. Use the `mkIOKey` macro to access the table.
static constexpr std::tuple<
mkIOKey(BeginInternalArrayListOutput), mkIOKey(BeginInternalArrayListInput),
mkIOKey(BeginInternalArrayFormattedOutput),
mkIOKey(BeginInternalArrayFormattedInput), mkIOKey(BeginInternalListOutput),
mkIOKey(BeginInternalListInput), mkIOKey(BeginInternalFormattedOutput),
mkIOKey(BeginInternalFormattedInput), mkIOKey(BeginInternalNamelistOutput),
mkIOKey(BeginInternalNamelistInput), mkIOKey(BeginExternalListOutput),
mkIOKey(BeginExternalListInput), mkIOKey(BeginExternalFormattedOutput),
mkIOKey(BeginExternalFormattedInput), mkIOKey(BeginUnformattedOutput),
mkIOKey(BeginUnformattedInput), mkIOKey(BeginExternalNamelistOutput),
mkIOKey(BeginExternalNamelistInput), mkIOKey(BeginAsynchronousOutput),
mkIOKey(BeginAsynchronousInput), mkIOKey(BeginWait), mkIOKey(BeginWaitAll),
mkIOKey(BeginClose), mkIOKey(BeginFlush), mkIOKey(BeginBackspace),
mkIOKey(BeginEndfile), mkIOKey(BeginRewind), mkIOKey(BeginOpenUnit),
mkIOKey(BeginOpenNewUnit), mkIOKey(BeginInquireUnit),
mkIOKey(BeginInquireFile), mkIOKey(BeginInquireIoLength),
mkIOKey(EnableHandlers), mkIOKey(SetAdvance), mkIOKey(SetBlank),
mkIOKey(SetDecimal), mkIOKey(SetDelim), mkIOKey(SetPad), mkIOKey(SetPos),
mkIOKey(SetRec), mkIOKey(SetRound), mkIOKey(SetSign),
mkIOKey(OutputDescriptor), mkIOKey(InputDescriptor),
mkIOKey(OutputUnformattedBlock), mkIOKey(InputUnformattedBlock),
mkIOKey(OutputInteger64), mkIOKey(InputInteger), mkIOKey(OutputReal32),
mkIOKey(InputReal32), mkIOKey(OutputReal64), mkIOKey(InputReal64),
mkIOKey(OutputComplex64), mkIOKey(OutputComplex32), mkIOKey(OutputAscii),
mkIOKey(InputAscii), mkIOKey(OutputLogical), mkIOKey(InputLogical),
mkIOKey(SetAccess), mkIOKey(SetAction), mkIOKey(SetAsynchronous),
mkIOKey(SetCarriagecontrol), mkIOKey(SetEncoding), mkIOKey(SetForm),
mkIOKey(SetPosition), mkIOKey(SetRecl), mkIOKey(SetStatus),
mkIOKey(SetFile), mkIOKey(GetNewUnit), mkIOKey(GetSize),
mkIOKey(GetIoLength), mkIOKey(GetIoMsg), mkIOKey(InquireCharacter),
mkIOKey(InquireLogical), mkIOKey(InquirePendingId),
mkIOKey(InquireInteger64), mkIOKey(EndIoStatement)>
newIOTable;
} // namespace Fortran::lower
namespace {
struct ConditionSpecifierInfo {
const Fortran::semantics::SomeExpr *ioStatExpr{};
const Fortran::semantics::SomeExpr *ioMsgExpr{};
bool hasErr{};
bool hasEnd{};
bool hasEor{};
/// Check for any condition specifier that applies to specifier processing.
bool hasErrorConditionSpecifier() const {
return ioStatExpr != nullptr || hasErr;
}
/// Check for any condition specifier that applies to data transfer items
/// in a PRINT, READ, WRITE, or WAIT statement. (WAIT may be irrelevant.)
bool hasTransferConditionSpecifier() const {
return ioStatExpr != nullptr || hasErr || hasEnd || hasEor;
}
/// Check for any condition specifier, including IOMSG.
bool hasAnyConditionSpecifier() const {
return ioStatExpr != nullptr || ioMsgExpr != nullptr || hasErr || hasEnd ||
hasEor;
}
};
} // namespace
using namespace Fortran::lower;
/// Helper function to retrieve the name of the IO function given the key `A`
template <typename A>
static constexpr const char *getName() {
return std::get<A>(newIOTable).name;
}
/// Helper function to retrieve the type model signature builder of the IO
/// function as defined by the key `A`
template <typename A>
static constexpr FuncTypeBuilderFunc getTypeModel() {
return std::get<A>(newIOTable).getTypeModel();
}
inline int64_t getLength(mlir::Type argTy) {
return argTy.cast<fir::SequenceType>().getShape()[0];
}
/// Get (or generate) the MLIR FuncOp for a given IO runtime function.
template <typename E>
static mlir::FuncOp getIORuntimeFunc(mlir::Location loc,
Fortran::lower::FirOpBuilder &builder) {
auto name = getName<E>();
auto func = builder.getNamedFunction(name);
if (func)
return func;
auto funTy = getTypeModel<E>()(builder.getContext());
func = builder.createFunction(loc, name, funTy);
func.setAttr("fir.runtime", builder.getUnitAttr());
func.setAttr("fir.io", builder.getUnitAttr());
return func;
}
/// Generate calls to end an IO statement. Return the IOSTAT value, if any.
/// It is the caller's responsibility to generate branches on that value.
static mlir::Value genEndIO(Fortran::lower::AbstractConverter &converter,
mlir::Location loc, mlir::Value cookie,
const ConditionSpecifierInfo &csi) {
auto &builder = converter.getFirOpBuilder();
if (csi.ioMsgExpr) {
auto getIoMsg = getIORuntimeFunc<mkIOKey(GetIoMsg)>(loc, builder);
auto ioMsgVar =
Fortran::lower::CharacterExprHelper{builder, loc}.createUnboxChar(
converter.genExprAddr(csi.ioMsgExpr, loc));
llvm::SmallVector<mlir::Value, 3> args{
cookie,
builder.createConvert(loc, getIoMsg.getType().getInput(1),
ioMsgVar.first),
builder.createConvert(loc, getIoMsg.getType().getInput(2),
ioMsgVar.second)};
builder.create<mlir::CallOp>(loc, getIoMsg, args);
}
auto endIoStatement = getIORuntimeFunc<mkIOKey(EndIoStatement)>(loc, builder);
llvm::SmallVector<mlir::Value, 1> endArgs{cookie};
auto call = builder.create<mlir::CallOp>(loc, endIoStatement, endArgs);
if (csi.ioStatExpr) {
auto ioStatVar = converter.genExprAddr(csi.ioStatExpr, loc);
auto ioStatResult = builder.createConvert(
loc, converter.genType(*csi.ioStatExpr), call.getResult(0));
builder.create<fir::StoreOp>(loc, ioStatResult, ioStatVar);
}
return csi.hasTransferConditionSpecifier() ? call.getResult(0)
: mlir::Value{};
}
/// Make the next call in the IO statement conditional on runtime result `ok`.
/// If a call returns `ok==false`, further suboperation calls for an I/O
/// statement will be skipped. This may generate branch heavy, deeply nested
/// conditionals for I/O statements with a large number of suboperations.
static void makeNextConditionalOn(Fortran::lower::FirOpBuilder &builder,
mlir::Location loc,
mlir::OpBuilder::InsertPoint &insertPt,
bool checkResult, mlir::Value ok,
bool inIterWhileLoop = false) {
if (!checkResult || !ok)
// Either I/O calls do not need to be checked, or the next I/O call is the
// first potentially fallable call.
return;
// A previous I/O call for a statement returned the bool `ok`. If this call
// is in a fir.iterate_while loop, the result must be propagated up to the
// loop scope. That is done in genIoLoop, but it is enabled here.
auto whereOp =
inIterWhileLoop
? builder.create<fir::WhereOp>(loc, builder.getI1Type(), ok, true)
: builder.create<fir::WhereOp>(loc, ok, /*withOtherwise=*/false);
if (!insertPt.isSet())
insertPt = builder.saveInsertionPoint();
builder.setInsertionPointToStart(&whereOp.whereRegion().front());
}
template <typename D>
static void genIoLoop(Fortran::lower::AbstractConverter &converter,
mlir::Value cookie, const D &ioImpliedDo,
bool checkResult, mlir::Value &ok, bool inIterWhileLoop);
/// Get the OutputXyz routine to output a value of the given type.
static mlir::FuncOp getOutputFunc(mlir::Location loc,
Fortran::lower::FirOpBuilder &builder,
mlir::Type type) {
if (auto ty = type.dyn_cast<mlir::IntegerType>())
return ty.getWidth() == 1
? getIORuntimeFunc<mkIOKey(OutputLogical)>(loc, builder)
: getIORuntimeFunc<mkIOKey(OutputInteger64)>(loc, builder);
if (auto ty = type.dyn_cast<mlir::FloatType>())
return ty.getWidth() <= 32
? getIORuntimeFunc<mkIOKey(OutputReal32)>(loc, builder)
: getIORuntimeFunc<mkIOKey(OutputReal64)>(loc, builder);
if (auto ty = type.dyn_cast<fir::CplxType>())
return ty.getFKind() <= 4
? getIORuntimeFunc<mkIOKey(OutputComplex32)>(loc, builder)
: getIORuntimeFunc<mkIOKey(OutputComplex64)>(loc, builder);
if (type.isa<fir::LogicalType>())
return getIORuntimeFunc<mkIOKey(OutputLogical)>(loc, builder);
if (type.isa<fir::BoxType>())
return getIORuntimeFunc<mkIOKey(OutputDescriptor)>(loc, builder);
if (Fortran::lower::CharacterExprHelper::isCharacter(type))
return getIORuntimeFunc<mkIOKey(OutputAscii)>(loc, builder);
// TODO: handle arrays
mlir::emitError(loc, "output for entity type ") << type << " not implemented";
return {};
}
/// Generate a sequence of output data transfer calls.
static void
genOutputItemList(Fortran::lower::AbstractConverter &converter,
mlir::Value cookie,
const std::list<Fortran::parser::OutputItem> &items,
mlir::OpBuilder::InsertPoint &insertPt, bool checkResult,
mlir::Value &ok, bool inIterWhileLoop) {
auto &builder = converter.getFirOpBuilder();
for (auto &item : items) {
if (const auto &impliedDo = std::get_if<1>(&item.u)) {
genIoLoop(converter, cookie, impliedDo->value(), checkResult, ok,
inIterWhileLoop);
continue;
}
auto &pExpr = std::get<Fortran::parser::Expr>(item.u);
auto loc = converter.genLocation(pExpr.source);
makeNextConditionalOn(builder, loc, insertPt, checkResult, ok,
inIterWhileLoop);
auto itemValue =
converter.genExprValue(Fortran::semantics::GetExpr(pExpr), loc);
auto itemType = itemValue.getType();
auto outputFunc = getOutputFunc(loc, builder, itemType);
auto argType = outputFunc.getType().getInput(1);
llvm::SmallVector<mlir::Value, 3> outputFuncArgs = {cookie};
Fortran::lower::CharacterExprHelper helper{builder, loc};
if (helper.isCharacter(itemType)) {
auto dataLen = helper.materializeCharacter(itemValue);
outputFuncArgs.push_back(builder.createConvert(
loc, outputFunc.getType().getInput(1), dataLen.first));
outputFuncArgs.push_back(builder.createConvert(
loc, outputFunc.getType().getInput(2), dataLen.second));
} else if (fir::isa_complex(itemType)) {
auto parts = Fortran::lower::ComplexExprHelper{builder, loc}.extractParts(
itemValue);
outputFuncArgs.push_back(parts.first);
outputFuncArgs.push_back(parts.second);
} else {
itemValue = builder.createConvert(loc, argType, itemValue);
outputFuncArgs.push_back(itemValue);
}
ok = builder.create<mlir::CallOp>(loc, outputFunc, outputFuncArgs)
.getResult(0);
}
}
/// Get the InputXyz routine to input a value of the given type.
static mlir::FuncOp getInputFunc(mlir::Location loc,
Fortran::lower::FirOpBuilder &builder,
mlir::Type type) {
if (auto ty = type.dyn_cast<mlir::IntegerType>())
return ty.getWidth() == 1
? getIORuntimeFunc<mkIOKey(InputLogical)>(loc, builder)
: getIORuntimeFunc<mkIOKey(InputInteger)>(loc, builder);
if (auto ty = type.dyn_cast<mlir::FloatType>())
return ty.getWidth() <= 32
? getIORuntimeFunc<mkIOKey(InputReal32)>(loc, builder)
: getIORuntimeFunc<mkIOKey(InputReal64)>(loc, builder);
if (auto ty = type.dyn_cast<fir::CplxType>())
return ty.getFKind() <= 4
? getIORuntimeFunc<mkIOKey(InputReal32)>(loc, builder)
: getIORuntimeFunc<mkIOKey(InputReal64)>(loc, builder);
if (type.isa<fir::LogicalType>())
return getIORuntimeFunc<mkIOKey(InputLogical)>(loc, builder);
if (type.isa<fir::BoxType>())
return getIORuntimeFunc<mkIOKey(InputDescriptor)>(loc, builder);
if (Fortran::lower::CharacterExprHelper::isCharacter(type))
return getIORuntimeFunc<mkIOKey(InputAscii)>(loc, builder);
// TODO: handle arrays
mlir::emitError(loc, "input for entity type ") << type << " not implemented";
return {};
}
/// Generate a sequence of input data transfer calls.
static void genInputItemList(Fortran::lower::AbstractConverter &converter,
mlir::Value cookie,
const std::list<Fortran::parser::InputItem> &items,
mlir::OpBuilder::InsertPoint &insertPt,
bool checkResult, mlir::Value &ok,
bool inIterWhileLoop) {
auto &builder = converter.getFirOpBuilder();
for (auto &item : items) {
if (const auto &impliedDo = std::get_if<1>(&item.u)) {
genIoLoop(converter, cookie, impliedDo->value(), checkResult, ok,
inIterWhileLoop);
continue;
}
auto &pVar = std::get<Fortran::parser::Variable>(item.u);
auto loc = converter.genLocation(pVar.GetSource());
makeNextConditionalOn(builder, loc, insertPt, checkResult, ok,
inIterWhileLoop);
auto itemAddr =
converter.genExprAddr(Fortran::semantics::GetExpr(pVar), loc);
auto itemType = itemAddr.getType().cast<fir::ReferenceType>().getEleTy();
auto inputFunc = getInputFunc(loc, builder, itemType);
auto argType = inputFunc.getType().getInput(1);
auto originalItemAddr = itemAddr;
mlir::Type complexPartType;
if (itemType.isa<fir::CplxType>())
complexPartType = builder.getRefType(
Fortran::lower::ComplexExprHelper{builder, loc}.getComplexPartType(
itemType));
auto complexPartAddr = [&](int index) {
return builder.create<fir::CoordinateOp>(
loc, complexPartType, originalItemAddr,
llvm::SmallVector<mlir::Value, 1>{builder.create<mlir::ConstantOp>(
loc, builder.getI32IntegerAttr(index))});
};
if (complexPartType)
itemAddr = complexPartAddr(0); // real part
itemAddr = builder.createConvert(loc, argType, itemAddr);
llvm::SmallVector<mlir::Value, 3> inputFuncArgs = {cookie, itemAddr};
Fortran::lower::CharacterExprHelper helper{builder, loc};
if (helper.isCharacter(itemType)) {
auto len = helper.materializeCharacter(originalItemAddr).second;
inputFuncArgs.push_back(
builder.createConvert(loc, inputFunc.getType().getInput(2), len));
} else if (itemType.isa<mlir::IntegerType>()) {
inputFuncArgs.push_back(builder.create<mlir::ConstantOp>(
loc, builder.getI32IntegerAttr(
itemType.cast<mlir::IntegerType>().getWidth() / 8)));
}
ok = builder.create<mlir::CallOp>(loc, inputFunc, inputFuncArgs)
.getResult(0);
if (complexPartType) { // imaginary part
makeNextConditionalOn(builder, loc, insertPt, checkResult, ok,
inIterWhileLoop);
inputFuncArgs = {cookie,
builder.createConvert(loc, argType, complexPartAddr(1))};
ok = builder.create<mlir::CallOp>(loc, inputFunc, inputFuncArgs)
.getResult(0);
}
}
}
/// Generate an io-implied-do loop.
template <typename D>
static void genIoLoop(Fortran::lower::AbstractConverter &converter,
mlir::Value cookie, const D &ioImpliedDo,
bool checkResult, mlir::Value &ok, bool inIterWhileLoop) {
mlir::OpBuilder::InsertPoint insertPt;
auto &builder = converter.getFirOpBuilder();
auto loc = converter.getCurrentLocation();
makeNextConditionalOn(builder, loc, insertPt, checkResult, ok,
inIterWhileLoop);
auto parentInsertPt = builder.saveInsertionPoint();
const auto &itemList = std::get<0>(ioImpliedDo.t);
const auto &control = std::get<1>(ioImpliedDo.t);
const auto &loopSym = *control.name.thing.thing.symbol;
auto loopVar = converter.getSymbolAddress(loopSym);
auto genFIRLoopIndex = [&](const Fortran::parser::ScalarIntExpr &expr) {
return builder.createConvert(
loc, builder.getIndexType(),
converter.genExprValue(*Fortran::semantics::GetExpr(expr)));
};
auto lowerValue = genFIRLoopIndex(control.lower);
auto upperValue = genFIRLoopIndex(control.upper);
auto stepValue = control.step.has_value()
? genFIRLoopIndex(*control.step)
: builder.create<mlir::ConstantIndexOp>(loc, 1);
auto genItemList = [&](const D &ioImpliedDo, bool inIterWhileLoop) {
if constexpr (std::is_same_v<D, Fortran::parser::InputImpliedDo>)
genInputItemList(converter, cookie, itemList, insertPt, checkResult, ok,
true);
else
genOutputItemList(converter, cookie, itemList, insertPt, checkResult, ok,
true);
};
if (!checkResult) {
// No I/O call result checks - the loop is a fir.do_loop op.
auto loopOp =
builder.create<fir::LoopOp>(loc, lowerValue, upperValue, stepValue);
builder.setInsertionPointToStart(loopOp.getBody());
auto lcv = builder.createConvert(loc, converter.genType(loopSym),
loopOp.getInductionVar());
builder.create<fir::StoreOp>(loc, lcv, loopVar);
insertPt = builder.saveInsertionPoint();
genItemList(ioImpliedDo, false);
builder.restoreInsertionPoint(parentInsertPt);
return;
}
// Check I/O call results - the loop is a fir.iterate_while op.
if (!ok)
ok = builder.createIntegerConstant(loc, builder.getI1Type(), 1);
fir::IterWhileOp iterWhileOp = builder.create<fir::IterWhileOp>(
loc, lowerValue, upperValue, stepValue, ok);
builder.setInsertionPointToStart(iterWhileOp.getBody());
auto lcv = builder.createConvert(loc, converter.genType(loopSym),
iterWhileOp.getInductionVar());
builder.create<fir::StoreOp>(loc, lcv, loopVar);
insertPt = builder.saveInsertionPoint();
ok = iterWhileOp.getIterateVar();
auto falseValue = builder.createIntegerConstant(loc, builder.getI1Type(), 0);
genItemList(ioImpliedDo, true);
// Unwind nested I/O call scopes, filling in true and false ResultOp's.
for (auto *op = builder.getBlock()->getParentOp(); isa<fir::WhereOp>(op);
op = op->getBlock()->getParentOp()) {
auto whereOp = dyn_cast<fir::WhereOp>(op);
auto *lastOp = &whereOp.whereRegion().front().back();
builder.setInsertionPointAfter(lastOp);
builder.create<fir::ResultOp>(loc, lastOp->getResult(0)); // runtime result
builder.setInsertionPointToStart(&whereOp.otherRegion().front());
builder.create<fir::ResultOp>(loc, falseValue); // known false result
}
builder.restoreInsertionPoint(insertPt);
builder.create<fir::ResultOp>(loc, builder.getBlock()->back().getResult(0));
ok = iterWhileOp.getResult(0);
builder.restoreInsertionPoint(parentInsertPt);
}
//===----------------------------------------------------------------------===//
// Default argument generation.
//===----------------------------------------------------------------------===//
static mlir::Value getDefaultFilename(Fortran::lower::FirOpBuilder &builder,
mlir::Location loc, mlir::Type toType) {
mlir::Value null =
builder.create<mlir::ConstantOp>(loc, builder.getI64IntegerAttr(0));
return builder.createConvert(loc, toType, null);
}
static mlir::Value getDefaultLineNo(Fortran::lower::FirOpBuilder &builder,
mlir::Location loc, mlir::Type toType) {
return builder.create<mlir::ConstantOp>(loc,
builder.getIntegerAttr(toType, 0));
}
static mlir::Value getDefaultScratch(Fortran::lower::FirOpBuilder &builder,
mlir::Location loc, mlir::Type toType) {
mlir::Value null =
builder.create<mlir::ConstantOp>(loc, builder.getI64IntegerAttr(0));
return builder.createConvert(loc, toType, null);
}
static mlir::Value getDefaultScratchLen(Fortran::lower::FirOpBuilder &builder,
mlir::Location loc, mlir::Type toType) {
return builder.create<mlir::ConstantOp>(loc,
builder.getIntegerAttr(toType, 0));
}
/// Lower a string literal. Many arguments to the runtime are conveyed as
/// Fortran CHARACTER literals.
template <typename A>
static std::tuple<mlir::Value, mlir::Value, mlir::Value>
lowerStringLit(Fortran::lower::AbstractConverter &converter, mlir::Location loc,
const A &syntax, mlir::Type strTy, mlir::Type lenTy,
mlir::Type ty2 = {}) {
auto &builder = converter.getFirOpBuilder();
auto *expr = Fortran::semantics::GetExpr(syntax);
auto str = converter.genExprValue(expr, loc);
Fortran::lower::CharacterExprHelper helper{builder, loc};
auto dataLen = helper.materializeCharacter(str);
auto buff = builder.createConvert(loc, strTy, dataLen.first);
auto len = builder.createConvert(loc, lenTy, dataLen.second);
if (ty2) {
auto kindVal = helper.getCharacterKind(str.getType());
auto kind = builder.create<mlir::ConstantOp>(
loc, builder.getIntegerAttr(ty2, kindVal));
return {buff, len, kind};
}
return {buff, len, mlir::Value{}};
}
/// Pass the body of the FORMAT statement in as if it were a CHARACTER literal
/// constant. NB: This is the prescribed manner in which the front-end passes
/// this information to lowering.
static std::tuple<mlir::Value, mlir::Value, mlir::Value>
lowerSourceTextAsStringLit(Fortran::lower::AbstractConverter &converter,
mlir::Location loc, llvm::StringRef text,
mlir::Type strTy, mlir::Type lenTy) {
text = text.drop_front(text.find('('));
text = text.take_front(text.rfind(')') + 1);
auto &builder = converter.getFirOpBuilder();
auto lit = builder.createStringLit(
loc, /*FIXME*/ fir::CharacterType::get(builder.getContext(), 1), text);
auto data =
Fortran::lower::CharacterExprHelper{builder, loc}.materializeCharacter(
lit);
auto buff = builder.createConvert(loc, strTy, data.first);
auto len = builder.createConvert(loc, lenTy, data.second);
return {buff, len, mlir::Value{}};
}
//===----------------------------------------------------------------------===//
// Handle I/O statement specifiers.
// These are threaded together for a single statement via the passed cookie.
//===----------------------------------------------------------------------===//
/// Generic to build an integral argument to the runtime.
template <typename A, typename B>
mlir::Value genIntIOOption(Fortran::lower::AbstractConverter &converter,
mlir::Location loc, mlir::Value cookie,
const B &spec) {
auto &builder = converter.getFirOpBuilder();
mlir::FuncOp ioFunc = getIORuntimeFunc<A>(loc, builder);
mlir::FunctionType ioFuncTy = ioFunc.getType();
auto expr = converter.genExprValue(Fortran::semantics::GetExpr(spec.v), loc);
auto val = builder.createConvert(loc, ioFuncTy.getInput(1), expr);
llvm::SmallVector<mlir::Value, 4> ioArgs = {cookie, val};
return builder.create<mlir::CallOp>(loc, ioFunc, ioArgs).getResult(0);
}
/// Generic to build a string argument to the runtime. This passes a CHARACTER
/// as a pointer to the buffer and a LEN parameter.
template <typename A, typename B>
mlir::Value genCharIOOption(Fortran::lower::AbstractConverter &converter,
mlir::Location loc, mlir::Value cookie,
const B &spec) {
auto &builder = converter.getFirOpBuilder();
mlir::FuncOp ioFunc = getIORuntimeFunc<A>(loc, builder);
mlir::FunctionType ioFuncTy = ioFunc.getType();
auto tup = lowerStringLit(converter, loc, spec, ioFuncTy.getInput(1),
ioFuncTy.getInput(2));
llvm::SmallVector<mlir::Value, 4> ioArgs = {cookie, std::get<0>(tup),
std::get<1>(tup)};
return builder.create<mlir::CallOp>(loc, ioFunc, ioArgs).getResult(0);
}
template <typename A>
mlir::Value genIOOption(Fortran::lower::AbstractConverter &converter,
mlir::Location loc, mlir::Value cookie, const A &spec) {
// default case: do nothing
return {};
}
template <>
mlir::Value genIOOption<Fortran::parser::FileNameExpr>(
Fortran::lower::AbstractConverter &converter, mlir::Location loc,
mlir::Value cookie, const Fortran::parser::FileNameExpr &spec) {
auto &builder = converter.getFirOpBuilder();
// has an extra KIND argument
auto ioFunc = getIORuntimeFunc<mkIOKey(SetFile)>(loc, builder);
mlir::FunctionType ioFuncTy = ioFunc.getType();
auto tup = lowerStringLit(converter, loc, spec, ioFuncTy.getInput(1),
ioFuncTy.getInput(2), ioFuncTy.getInput(3));
llvm::SmallVector<mlir::Value, 4> ioArgs{cookie, std::get<0>(tup),
std::get<1>(tup), std::get<2>(tup)};
return builder.create<mlir::CallOp>(loc, ioFunc, ioArgs).getResult(0);
}
template <>
mlir::Value genIOOption<Fortran::parser::ConnectSpec::CharExpr>(
Fortran::lower::AbstractConverter &converter, mlir::Location loc,
mlir::Value cookie, const Fortran::parser::ConnectSpec::CharExpr &spec) {
auto &builder = converter.getFirOpBuilder();
mlir::FuncOp ioFunc;
switch (std::get<Fortran::parser::ConnectSpec::CharExpr::Kind>(spec.t)) {
case Fortran::parser::ConnectSpec::CharExpr::Kind::Access:
ioFunc = getIORuntimeFunc<mkIOKey(SetAccess)>(loc, builder);
break;
case Fortran::parser::ConnectSpec::CharExpr::Kind::Action:
ioFunc = getIORuntimeFunc<mkIOKey(SetAction)>(loc, builder);
break;
case Fortran::parser::ConnectSpec::CharExpr::Kind::Asynchronous:
ioFunc = getIORuntimeFunc<mkIOKey(SetAsynchronous)>(loc, builder);
break;
case Fortran::parser::ConnectSpec::CharExpr::Kind::Blank:
ioFunc = getIORuntimeFunc<mkIOKey(SetBlank)>(loc, builder);
break;
case Fortran::parser::ConnectSpec::CharExpr::Kind::Decimal:
ioFunc = getIORuntimeFunc<mkIOKey(SetDecimal)>(loc, builder);
break;
case Fortran::parser::ConnectSpec::CharExpr::Kind::Delim:
ioFunc = getIORuntimeFunc<mkIOKey(SetDelim)>(loc, builder);
break;
case Fortran::parser::ConnectSpec::CharExpr::Kind::Encoding:
ioFunc = getIORuntimeFunc<mkIOKey(SetEncoding)>(loc, builder);
break;
case Fortran::parser::ConnectSpec::CharExpr::Kind::Form:
ioFunc = getIORuntimeFunc<mkIOKey(SetForm)>(loc, builder);
break;
case Fortran::parser::ConnectSpec::CharExpr::Kind::Pad:
ioFunc = getIORuntimeFunc<mkIOKey(SetPad)>(loc, builder);
break;
case Fortran::parser::ConnectSpec::CharExpr::Kind::Position:
ioFunc = getIORuntimeFunc<mkIOKey(SetPosition)>(loc, builder);
break;
case Fortran::parser::ConnectSpec::CharExpr::Kind::Round:
ioFunc = getIORuntimeFunc<mkIOKey(SetRound)>(loc, builder);
break;
case Fortran::parser::ConnectSpec::CharExpr::Kind::Sign:
ioFunc = getIORuntimeFunc<mkIOKey(SetSign)>(loc, builder);
break;
case Fortran::parser::ConnectSpec::CharExpr::Kind::Carriagecontrol:
ioFunc = getIORuntimeFunc<mkIOKey(SetCarriagecontrol)>(loc, builder);
break;
case Fortran::parser::ConnectSpec::CharExpr::Kind::Convert:
llvm_unreachable("CONVERT not part of the runtime::io interface");
case Fortran::parser::ConnectSpec::CharExpr::Kind::Dispose:
llvm_unreachable("DISPOSE not part of the runtime::io interface");
}
mlir::FunctionType ioFuncTy = ioFunc.getType();
auto tup = lowerStringLit(
converter, loc, std::get<Fortran::parser::ScalarDefaultCharExpr>(spec.t),
ioFuncTy.getInput(1), ioFuncTy.getInput(2));
llvm::SmallVector<mlir::Value, 4> ioArgs = {cookie, std::get<0>(tup),
std::get<1>(tup)};
return builder.create<mlir::CallOp>(loc, ioFunc, ioArgs).getResult(0);
}
template <>
mlir::Value genIOOption<Fortran::parser::ConnectSpec::Recl>(
Fortran::lower::AbstractConverter &converter, mlir::Location loc,
mlir::Value cookie, const Fortran::parser::ConnectSpec::Recl &spec) {
return genIntIOOption<mkIOKey(SetRecl)>(converter, loc, cookie, spec);
}
template <>
mlir::Value genIOOption<Fortran::parser::StatusExpr>(
Fortran::lower::AbstractConverter &converter, mlir::Location loc,
mlir::Value cookie, const Fortran::parser::StatusExpr &spec) {
return genCharIOOption<mkIOKey(SetStatus)>(converter, loc, cookie, spec.v);
}
template <>
mlir::Value
genIOOption<Fortran::parser::Name>(Fortran::lower::AbstractConverter &converter,
mlir::Location loc, mlir::Value cookie,
const Fortran::parser::Name &spec) {
// namelist
llvm_unreachable("not implemented");
}
template <>
mlir::Value genIOOption<Fortran::parser::IoControlSpec::CharExpr>(
Fortran::lower::AbstractConverter &converter, mlir::Location loc,
mlir::Value cookie, const Fortran::parser::IoControlSpec::CharExpr &spec) {
auto &builder = converter.getFirOpBuilder();
mlir::FuncOp ioFunc;
switch (std::get<Fortran::parser::IoControlSpec::CharExpr::Kind>(spec.t)) {
case Fortran::parser::IoControlSpec::CharExpr::Kind::Advance:
ioFunc = getIORuntimeFunc<mkIOKey(SetAdvance)>(loc, builder);
break;
case Fortran::parser::IoControlSpec::CharExpr::Kind::Blank:
ioFunc = getIORuntimeFunc<mkIOKey(SetBlank)>(loc, builder);
break;
case Fortran::parser::IoControlSpec::CharExpr::Kind::Decimal:
ioFunc = getIORuntimeFunc<mkIOKey(SetDecimal)>(loc, builder);
break;
case Fortran::parser::IoControlSpec::CharExpr::Kind::Delim:
ioFunc = getIORuntimeFunc<mkIOKey(SetDelim)>(loc, builder);
break;
case Fortran::parser::IoControlSpec::CharExpr::Kind::Pad:
ioFunc = getIORuntimeFunc<mkIOKey(SetPad)>(loc, builder);
break;
case Fortran::parser::IoControlSpec::CharExpr::Kind::Round:
ioFunc = getIORuntimeFunc<mkIOKey(SetRound)>(loc, builder);
break;
case Fortran::parser::IoControlSpec::CharExpr::Kind::Sign:
ioFunc = getIORuntimeFunc<mkIOKey(SetSign)>(loc, builder);
break;
}
mlir::FunctionType ioFuncTy = ioFunc.getType();
auto tup = lowerStringLit(
converter, loc, std::get<Fortran::parser::ScalarDefaultCharExpr>(spec.t),
ioFuncTy.getInput(1), ioFuncTy.getInput(2));
llvm::SmallVector<mlir::Value, 4> ioArgs = {cookie, std::get<0>(tup),
std::get<1>(tup)};
return builder.create<mlir::CallOp>(loc, ioFunc, ioArgs).getResult(0);
}
template <>
mlir::Value genIOOption<Fortran::parser::IoControlSpec::Asynchronous>(
Fortran::lower::AbstractConverter &converter, mlir::Location loc,
mlir::Value cookie,
const Fortran::parser::IoControlSpec::Asynchronous &spec) {
return genCharIOOption<mkIOKey(SetAsynchronous)>(converter, loc, cookie,
spec.v);
}
template <>
mlir::Value genIOOption<Fortran::parser::IdVariable>(
Fortran::lower::AbstractConverter &converter, mlir::Location loc,
mlir::Value cookie, const Fortran::parser::IdVariable &spec) {
llvm_unreachable("asynchronous ID not implemented");
}
template <>
mlir::Value genIOOption<Fortran::parser::IoControlSpec::Pos>(
Fortran::lower::AbstractConverter &converter, mlir::Location loc,
mlir::Value cookie, const Fortran::parser::IoControlSpec::Pos &spec) {
return genIntIOOption<mkIOKey(SetPos)>(converter, loc, cookie, spec);
}
template <>
mlir::Value genIOOption<Fortran::parser::IoControlSpec::Rec>(
Fortran::lower::AbstractConverter &converter, mlir::Location loc,
mlir::Value cookie, const Fortran::parser::IoControlSpec::Rec &spec) {
return genIntIOOption<mkIOKey(SetRec)>(converter, loc, cookie, spec);
}
//===----------------------------------------------------------------------===//
// Gather I/O statement condition specifier information (if any).
//===----------------------------------------------------------------------===//
template <typename SEEK, typename A>
static bool hasX(const A &list) {
for (const auto &spec : list)
if (std::holds_alternative<SEEK>(spec.u))
return true;
return false;
}
template <typename SEEK, typename A>
static bool hasMem(const A &stmt) {
return hasX<SEEK>(stmt.v);
}
/// Get the sought expression from the specifier list.
template <typename SEEK, typename A>
static const Fortran::semantics::SomeExpr *getExpr(const A &stmt) {
for (const auto &spec : stmt.v)
if (auto *f = std::get_if<SEEK>(&spec.u))
return Fortran::semantics::GetExpr(f->v);
llvm_unreachable("must have a file unit");
}
/// For each specifier, build the appropriate call, threading the cookie, and
/// returning the insertion point as to the initial context. If there are no
/// specifiers, the insertion point is undefined.
template <typename A>
static mlir::OpBuilder::InsertPoint
threadSpecs(Fortran::lower::AbstractConverter &converter, mlir::Location loc,
mlir::Value cookie, const A &specList, bool checkResult,
mlir::Value &ok) {
auto &builder = converter.getFirOpBuilder();
mlir::OpBuilder::InsertPoint insertPt;
for (const auto &spec : specList) {
makeNextConditionalOn(builder, loc, insertPt, checkResult, ok);
ok = std::visit(Fortran::common::visitors{[&](const auto &x) {
return genIOOption(converter, loc, cookie, x);
}},
spec.u);
}
return insertPt;
}
template <typename A>
static void
genConditionHandlerCall(Fortran::lower::AbstractConverter &converter,
mlir::Location loc, mlir::Value cookie,
const A &specList, ConditionSpecifierInfo &csi) {
for (const auto &spec : specList) {
std::visit(
Fortran::common::visitors{
[&](const Fortran::parser::StatVariable &msgVar) {
csi.ioStatExpr = Fortran::semantics::GetExpr(msgVar);
},
[&](const Fortran::parser::MsgVariable &msgVar) {
csi.ioMsgExpr = Fortran::semantics::GetExpr(msgVar);
},
[&](const Fortran::parser::EndLabel &) { csi.hasEnd = true; },
[&](const Fortran::parser::EorLabel &) { csi.hasEor = true; },
[&](const Fortran::parser::ErrLabel &) { csi.hasErr = true; },
[](const auto &) {}},
spec.u);
}
if (!csi.hasAnyConditionSpecifier())
return;
auto &builder = converter.getFirOpBuilder();
mlir::FuncOp enableHandlers =
getIORuntimeFunc<mkIOKey(EnableHandlers)>(loc, builder);
mlir::Type boolType = enableHandlers.getType().getInput(1);
auto boolValue = [&](bool specifierIsPresent) {
return builder.create<mlir::ConstantOp>(
loc, builder.getIntegerAttr(boolType, specifierIsPresent));
};
llvm::SmallVector<mlir::Value, 6> ioArgs = {
cookie,
boolValue(csi.ioStatExpr != nullptr),
boolValue(csi.hasErr),
boolValue(csi.hasEnd),
boolValue(csi.hasEor),
boolValue(csi.ioMsgExpr != nullptr)};
builder.create<mlir::CallOp>(loc, enableHandlers, ioArgs);
}
//===----------------------------------------------------------------------===//
// Data transfer helpers
//===----------------------------------------------------------------------===//
template <typename SEEK, typename A>
static bool hasIOControl(const A &stmt) {
return hasX<SEEK>(stmt.controls);
}
template <typename SEEK, typename A>
static const auto *getIOControl(const A &stmt) {
for (const auto &spec : stmt.controls)
if (const auto *result = std::get_if<SEEK>(&spec.u))
return result;
return static_cast<const SEEK *>(nullptr);
}
/// returns true iff the expression in the parse tree is not really a format but
/// rather a namelist variable.
template <typename A>
static bool formatIsActuallyNamelist(const A &format) {
if (auto *e = std::get_if<Fortran::parser::Expr>(&format.u)) {
auto *expr = Fortran::semantics::GetExpr(*e);
if (const Fortran::semantics::Symbol *y =
Fortran::evaluate::UnwrapWholeSymbolDataRef(*expr))
return y->has<Fortran::semantics::NamelistDetails>();
}
return false;
}
template <typename A>
static bool isDataTransferFormatted(const A &stmt) {
if (stmt.format)
return !formatIsActuallyNamelist(*stmt.format);
return hasIOControl<Fortran::parser::Format>(stmt);
}
template <>
constexpr bool isDataTransferFormatted<Fortran::parser::PrintStmt>(
const Fortran::parser::PrintStmt &) {
return true; // PRINT is always formatted
}
template <typename A>
static bool isDataTransferList(const A &stmt) {
if (stmt.format)
return std::holds_alternative<Fortran::parser::Star>(stmt.format->u);
if (auto *mem = getIOControl<Fortran::parser::Format>(stmt))
return std::holds_alternative<Fortran::parser::Star>(mem->u);
return false;
}
template <>
bool isDataTransferList<Fortran::parser::PrintStmt>(
const Fortran::parser::PrintStmt &stmt) {
return std::holds_alternative<Fortran::parser::Star>(
std::get<Fortran::parser::Format>(stmt.t).u);
}
template <typename A>
static bool isDataTransferInternal(const A &stmt) {
if (stmt.iounit.has_value())
return std::holds_alternative<Fortran::parser::Variable>(stmt.iounit->u);
if (auto *unit = getIOControl<Fortran::parser::IoUnit>(stmt))
return std::holds_alternative<Fortran::parser::Variable>(unit->u);
return false;
}
template <>
constexpr bool isDataTransferInternal<Fortran::parser::PrintStmt>(
const Fortran::parser::PrintStmt &) {
return false;
}
static bool hasNonDefaultCharKind(const Fortran::parser::Variable &var) {
// TODO
return false;
}
template <typename A>
static bool isDataTransferInternalNotDefaultKind(const A &stmt) {
// same as isDataTransferInternal, but the KIND of the expression is not the
// default KIND.
if (stmt.iounit.has_value())
if (auto *var = std::get_if<Fortran::parser::Variable>(&stmt.iounit->u))
return hasNonDefaultCharKind(*var);
if (auto *unit = getIOControl<Fortran::parser::IoUnit>(stmt))
if (auto *var = std::get_if<Fortran::parser::Variable>(&unit->u))
return hasNonDefaultCharKind(*var);
return false;
}
template <>
constexpr bool isDataTransferInternalNotDefaultKind<Fortran::parser::PrintStmt>(
const Fortran::parser::PrintStmt &) {
return false;
}
template <typename A>
static bool isDataTransferAsynchronous(const A &stmt) {
if (auto *asynch =
getIOControl<Fortran::parser::IoControlSpec::Asynchronous>(stmt)) {
// FIXME: should contain a string of YES or NO
llvm_unreachable("asynchronous transfers not implemented in runtime");
}
return false;
}
template <>
constexpr bool isDataTransferAsynchronous<Fortran::parser::PrintStmt>(
const Fortran::parser::PrintStmt &) {
return false;
}
template <typename A>
static bool isDataTransferNamelist(const A &stmt) {
if (stmt.format)
return formatIsActuallyNamelist(*stmt.format);
return hasIOControl<Fortran::parser::Name>(stmt);
}
template <>
constexpr bool isDataTransferNamelist<Fortran::parser::PrintStmt>(
const Fortran::parser::PrintStmt &) {
return false;
}
/// Generate a reference to a format string. There are four cases - a format
/// statement label, a character format expression, an integer that holds the
/// label of a format statement, and the * case. The first three are done here.
/// The * case is done elsewhere.
static std::tuple<mlir::Value, mlir::Value, mlir::Value>
genFormat(Fortran::lower::AbstractConverter &converter, mlir::Location loc,
const Fortran::parser::Format &format, mlir::Type strTy,
mlir::Type lenTy, Fortran::lower::pft::LabelEvalMap &labelMap,
Fortran::lower::pft::SymbolLabelMap &assignMap) {
if (const auto *label = std::get_if<Fortran::parser::Label>(&format.u)) {
// format statement label
auto iter = labelMap.find(*label);
assert(iter != labelMap.end() && "FORMAT not found in PROCEDURE");
return lowerSourceTextAsStringLit(
converter, loc, toStringRef(iter->second->position), strTy, lenTy);
}
const auto *pExpr = std::get_if<Fortran::parser::Expr>(&format.u);
assert(pExpr && "missing format expression");
auto e = Fortran::semantics::GetExpr(*pExpr);
if (Fortran::semantics::ExprHasTypeCategory(
*e, Fortran::common::TypeCategory::Character))
// character expression
return lowerStringLit(converter, loc, *pExpr, strTy, lenTy);
// integer variable containing an ASSIGN label
assert(Fortran::semantics::ExprHasTypeCategory(
*e, Fortran::common::TypeCategory::Integer));
// TODO - implement this
llvm::report_fatal_error(
"using a variable to reference a FORMAT statement; not implemented yet");
}
template <typename A>
std::tuple<mlir::Value, mlir::Value, mlir::Value>
getFormat(Fortran::lower::AbstractConverter &converter, mlir::Location loc,
const A &stmt, mlir::Type strTy, mlir::Type lenTy,
Fortran::lower::pft::LabelEvalMap &labelMap,
Fortran::lower::pft::SymbolLabelMap &assignMap) {
if (stmt.format && !formatIsActuallyNamelist(*stmt.format))
return genFormat(converter, loc, *stmt.format, strTy, lenTy, labelMap,
assignMap);
return genFormat(converter, loc, *getIOControl<Fortran::parser::Format>(stmt),
strTy, lenTy, labelMap, assignMap);
}
template <>
std::tuple<mlir::Value, mlir::Value, mlir::Value>
getFormat<Fortran::parser::PrintStmt>(
Fortran::lower::AbstractConverter &converter, mlir::Location loc,
const Fortran::parser::PrintStmt &stmt, mlir::Type strTy, mlir::Type lenTy,
Fortran::lower::pft::LabelEvalMap &labelMap,
Fortran::lower::pft::SymbolLabelMap &assignMap) {
return genFormat(converter, loc, std::get<Fortran::parser::Format>(stmt.t),
strTy, lenTy, labelMap, assignMap);
}
static std::tuple<mlir::Value, mlir::Value, mlir::Value>
genBuffer(Fortran::lower::AbstractConverter &converter, mlir::Location loc,
const Fortran::parser::IoUnit &iounit, mlir::Type strTy,
mlir::Type lenTy) {
[[maybe_unused]] auto &var = std::get<Fortran::parser::Variable>(iounit.u);
TODO();
}
template <typename A>
std::tuple<mlir::Value, mlir::Value, mlir::Value>
getBuffer(Fortran::lower::AbstractConverter &converter, mlir::Location loc,
const A &stmt, mlir::Type strTy, mlir::Type lenTy) {
if (stmt.iounit)
return genBuffer(converter, loc, *stmt.iounit, strTy, lenTy);
return genBuffer(converter, loc, *getIOControl<Fortran::parser::IoUnit>(stmt),
strTy, lenTy);
}
template <typename A>
mlir::Value getDescriptor(Fortran::lower::AbstractConverter &converter,
mlir::Location loc, const A &stmt,
mlir::Type toType) {
TODO();
}
static mlir::Value genIOUnit(Fortran::lower::AbstractConverter &converter,
mlir::Location loc,
const Fortran::parser::IoUnit &iounit,
mlir::Type ty) {
auto &builder = converter.getFirOpBuilder();
if (auto *e = std::get_if<Fortran::parser::FileUnitNumber>(&iounit.u)) {
auto ex = converter.genExprValue(Fortran::semantics::GetExpr(*e), loc);
return builder.createConvert(loc, ty, ex);
}
return builder.create<mlir::ConstantOp>(
loc, builder.getIntegerAttr(ty, Fortran::runtime::io::DefaultUnit));
}
template <typename A>
mlir::Value getIOUnit(Fortran::lower::AbstractConverter &converter,
mlir::Location loc, const A &stmt, mlir::Type ty) {
if (stmt.iounit)
return genIOUnit(converter, loc, *stmt.iounit, ty);
return genIOUnit(converter, loc, *getIOControl<Fortran::parser::IoUnit>(stmt),
ty);
}
//===----------------------------------------------------------------------===//
// Generators for each I/O statement type.
//===----------------------------------------------------------------------===//
template <typename K, typename S>
static mlir::Value genBasicIOStmt(Fortran::lower::AbstractConverter &converter,
const S &stmt) {
auto &builder = converter.getFirOpBuilder();
auto loc = converter.getCurrentLocation();
auto beginFunc = getIORuntimeFunc<K>(loc, builder);
mlir::FunctionType beginFuncTy = beginFunc.getType();
auto unit = converter.genExprValue(
getExpr<Fortran::parser::FileUnitNumber>(stmt), loc);
auto un = builder.createConvert(loc, beginFuncTy.getInput(0), unit);
auto file = getDefaultFilename(builder, loc, beginFuncTy.getInput(1));
auto line = getDefaultLineNo(builder, loc, beginFuncTy.getInput(2));
llvm::SmallVector<mlir::Value, 4> args{un, file, line};
auto cookie = builder.create<mlir::CallOp>(loc, beginFunc, args).getResult(0);
ConditionSpecifierInfo csi{};
genConditionHandlerCall(converter, loc, cookie, stmt.v, csi);
mlir::Value ok{};
auto insertPt = threadSpecs(converter, loc, cookie, stmt.v,
csi.hasErrorConditionSpecifier(), ok);
if (insertPt.isSet())
builder.restoreInsertionPoint(insertPt);
return genEndIO(converter, converter.getCurrentLocation(), cookie, csi);
}
mlir::Value Fortran::lower::genBackspaceStatement(
Fortran::lower::AbstractConverter &converter,
const Fortran::parser::BackspaceStmt &stmt) {
return genBasicIOStmt<mkIOKey(BeginBackspace)>(converter, stmt);
}
mlir::Value Fortran::lower::genEndfileStatement(
Fortran::lower::AbstractConverter &converter,
const Fortran::parser::EndfileStmt &stmt) {
return genBasicIOStmt<mkIOKey(BeginEndfile)>(converter, stmt);
}
mlir::Value
Fortran::lower::genFlushStatement(Fortran::lower::AbstractConverter &converter,
const Fortran::parser::FlushStmt &stmt) {
return genBasicIOStmt<mkIOKey(BeginFlush)>(converter, stmt);
}
mlir::Value
Fortran::lower::genRewindStatement(Fortran::lower::AbstractConverter &converter,
const Fortran::parser::RewindStmt &stmt) {
return genBasicIOStmt<mkIOKey(BeginRewind)>(converter, stmt);
}
mlir::Value
Fortran::lower::genOpenStatement(Fortran::lower::AbstractConverter &converter,
const Fortran::parser::OpenStmt &stmt) {
auto &builder = converter.getFirOpBuilder();
mlir::FuncOp beginFunc;
llvm::SmallVector<mlir::Value, 4> beginArgs;
auto loc = converter.getCurrentLocation();
if (hasMem<Fortran::parser::FileUnitNumber>(stmt)) {
beginFunc = getIORuntimeFunc<mkIOKey(BeginOpenUnit)>(loc, builder);
mlir::FunctionType beginFuncTy = beginFunc.getType();
auto unit = converter.genExprValue(
getExpr<Fortran::parser::FileUnitNumber>(stmt), loc);
beginArgs.push_back(
builder.createConvert(loc, beginFuncTy.getInput(0), unit));
beginArgs.push_back(
getDefaultFilename(builder, loc, beginFuncTy.getInput(1)));
beginArgs.push_back(
getDefaultLineNo(builder, loc, beginFuncTy.getInput(2)));
} else {
assert(hasMem<Fortran::parser::ConnectSpec::Newunit>(stmt));
beginFunc = getIORuntimeFunc<mkIOKey(BeginOpenNewUnit)>(loc, builder);
mlir::FunctionType beginFuncTy = beginFunc.getType();
beginArgs.push_back(
getDefaultFilename(builder, loc, beginFuncTy.getInput(0)));
beginArgs.push_back(
getDefaultLineNo(builder, loc, beginFuncTy.getInput(1)));
}
auto cookie =
builder.create<mlir::CallOp>(loc, beginFunc, beginArgs).getResult(0);
ConditionSpecifierInfo csi{};
genConditionHandlerCall(converter, loc, cookie, stmt.v, csi);
mlir::Value ok{};
auto insertPt = threadSpecs(converter, loc, cookie, stmt.v,
csi.hasErrorConditionSpecifier(), ok);
if (insertPt.isSet())
builder.restoreInsertionPoint(insertPt);
return genEndIO(converter, loc, cookie, csi);
}
mlir::Value
Fortran::lower::genCloseStatement(Fortran::lower::AbstractConverter &converter,
const Fortran::parser::CloseStmt &stmt) {
return genBasicIOStmt<mkIOKey(BeginClose)>(converter, stmt);
}
mlir::Value
Fortran::lower::genWaitStatement(Fortran::lower::AbstractConverter &converter,
const Fortran::parser::WaitStmt &stmt) {
auto &builder = converter.getFirOpBuilder();
auto loc = converter.getCurrentLocation();
bool hasId = hasMem<Fortran::parser::IdExpr>(stmt);
mlir::FuncOp beginFunc =
hasId ? getIORuntimeFunc<mkIOKey(BeginWait)>(loc, builder)
: getIORuntimeFunc<mkIOKey(BeginWaitAll)>(loc, builder);
mlir::FunctionType beginFuncTy = beginFunc.getType();
auto unit = converter.genExprValue(
getExpr<Fortran::parser::FileUnitNumber>(stmt), loc);
auto un = builder.createConvert(loc, beginFuncTy.getInput(0), unit);
llvm::SmallVector<mlir::Value, 4> args{un};
if (hasId) {
auto id =
converter.genExprValue(getExpr<Fortran::parser::IdExpr>(stmt), loc);
args.push_back(builder.createConvert(loc, beginFuncTy.getInput(1), id));
}
auto cookie = builder.create<mlir::CallOp>(loc, beginFunc, args).getResult(0);
ConditionSpecifierInfo csi{};
genConditionHandlerCall(converter, loc, cookie, stmt.v, csi);
return genEndIO(converter, converter.getCurrentLocation(), cookie, csi);
}
//===----------------------------------------------------------------------===//
// Data transfer statements.
//
// There are several dimensions to the API with regard to data transfer
// statements that need to be considered.
//
// - input (READ) vs. output (WRITE, PRINT)
// - formatted vs. list vs. unformatted
// - synchronous vs. asynchronous
// - namelist vs. list
// - external vs. internal + default KIND vs. internal + other KIND
//===----------------------------------------------------------------------===//
// Determine the correct BeginXyz{In|Out}put api to invoke.
template <bool isInput>
mlir::FuncOp getBeginDataTransfer(mlir::Location loc, FirOpBuilder &builder,
bool isFormatted, bool isList, bool isIntern,
bool isOtherIntern, bool isAsynch,
bool isNml) {
if constexpr (isInput) {
if (isAsynch)
return getIORuntimeFunc<mkIOKey(BeginAsynchronousInput)>(loc, builder);
if (isFormatted) {
if (isIntern) {
if (isNml)
return getIORuntimeFunc<mkIOKey(BeginInternalNamelistInput)>(loc,
builder);
if (isOtherIntern) {
if (isList)
return getIORuntimeFunc<mkIOKey(BeginInternalArrayListInput)>(
loc, builder);
return getIORuntimeFunc<mkIOKey(BeginInternalArrayFormattedInput)>(
loc, builder);
}
if (isList)
return getIORuntimeFunc<mkIOKey(BeginInternalListInput)>(loc,
builder);
return getIORuntimeFunc<mkIOKey(BeginInternalFormattedInput)>(loc,
builder);
}
if (isNml)
return getIORuntimeFunc<mkIOKey(BeginExternalNamelistInput)>(loc,
builder);
if (isList)
return getIORuntimeFunc<mkIOKey(BeginExternalListInput)>(loc, builder);
return getIORuntimeFunc<mkIOKey(BeginExternalFormattedInput)>(loc,
builder);
}
return getIORuntimeFunc<mkIOKey(BeginUnformattedInput)>(loc, builder);
} else {
if (isAsynch)
return getIORuntimeFunc<mkIOKey(BeginAsynchronousOutput)>(loc, builder);
if (isFormatted) {
if (isIntern) {
if (isNml)
return getIORuntimeFunc<mkIOKey(BeginInternalNamelistOutput)>(
loc, builder);
if (isOtherIntern) {
if (isList)
return getIORuntimeFunc<mkIOKey(BeginInternalArrayListOutput)>(
loc, builder);
return getIORuntimeFunc<mkIOKey(BeginInternalArrayFormattedOutput)>(
loc, builder);
}
if (isList)
return getIORuntimeFunc<mkIOKey(BeginInternalListOutput)>(loc,
builder);
return getIORuntimeFunc<mkIOKey(BeginInternalFormattedOutput)>(loc,
builder);
}
if (isNml)
return getIORuntimeFunc<mkIOKey(BeginExternalNamelistOutput)>(loc,
builder);
if (isList)
return getIORuntimeFunc<mkIOKey(BeginExternalListOutput)>(loc, builder);
return getIORuntimeFunc<mkIOKey(BeginExternalFormattedOutput)>(loc,
builder);
}
return getIORuntimeFunc<mkIOKey(BeginUnformattedOutput)>(loc, builder);
}
}
/// Generate the arguments of a BeginXyz call.
template <bool hasIOCtrl, typename A>
void genBeginCallArguments(llvm::SmallVector<mlir::Value, 8> &ioArgs,
Fortran::lower::AbstractConverter &converter,
mlir::Location loc, const A &stmt,
mlir::FunctionType ioFuncTy, bool isFormatted,
bool isList, bool isIntern, bool isOtherIntern,
bool isAsynch, bool isNml,
Fortran::lower::pft::LabelEvalMap &labelMap,
Fortran::lower::pft::SymbolLabelMap &assignMap) {
auto &builder = converter.getFirOpBuilder();
if constexpr (hasIOCtrl) {
// READ/WRITE cases have a wide variety of argument permutations
if (isAsynch || !isFormatted) {
// unit (always first), ...
ioArgs.push_back(
getIOUnit(converter, loc, stmt, ioFuncTy.getInput(ioArgs.size())));
if (isAsynch) {
// unknown-thingy, [buff, LEN]
llvm_unreachable("not implemented");
}
return;
}
assert(isFormatted && "formatted data transfer");
if (!isIntern) {
if (isNml) {
// namelist group, ...
llvm_unreachable("not implemented");
} else if (!isList) {
// | [format, LEN], ...
auto pair = getFormat(
converter, loc, stmt, ioFuncTy.getInput(ioArgs.size()),
ioFuncTy.getInput(ioArgs.size() + 1), labelMap, assignMap);
ioArgs.push_back(std::get<0>(pair));
ioArgs.push_back(std::get<1>(pair));
}
// unit (always last)
ioArgs.push_back(
getIOUnit(converter, loc, stmt, ioFuncTy.getInput(ioArgs.size())));
return;
}
assert(isIntern && "internal data transfer");
if (isNml || isOtherIntern) {
// descriptor, ...
ioArgs.push_back(getDescriptor(converter, loc, stmt,
ioFuncTy.getInput(ioArgs.size())));
if (isNml) {
// namelist group, ...
llvm_unreachable("not implemented");
} else if (isOtherIntern && !isList) {
// | [format, LEN], ...
auto pair = getFormat(
converter, loc, stmt, ioFuncTy.getInput(ioArgs.size()),
ioFuncTy.getInput(ioArgs.size() + 1), labelMap, assignMap);
ioArgs.push_back(std::get<0>(pair));
ioArgs.push_back(std::get<1>(pair));
}
} else {
// | [buff, LEN], ...
auto pair =
getBuffer(converter, loc, stmt, ioFuncTy.getInput(ioArgs.size()),
ioFuncTy.getInput(ioArgs.size() + 1));
ioArgs.push_back(std::get<0>(pair));
ioArgs.push_back(std::get<1>(pair));
if (!isList) {
// [format, LEN], ...
auto pair = getFormat(
converter, loc, stmt, ioFuncTy.getInput(ioArgs.size()),
ioFuncTy.getInput(ioArgs.size() + 1), labelMap, assignMap);
ioArgs.push_back(std::get<0>(pair));
ioArgs.push_back(std::get<1>(pair));
}
}
// [scratch, LEN] (always last)
ioArgs.push_back(
getDefaultScratch(builder, loc, ioFuncTy.getInput(ioArgs.size())));
ioArgs.push_back(
getDefaultScratchLen(builder, loc, ioFuncTy.getInput(ioArgs.size())));
} else {
if (!isList) {
// [format, LEN], ...
auto pair =
getFormat(converter, loc, stmt, ioFuncTy.getInput(ioArgs.size()),
ioFuncTy.getInput(ioArgs.size() + 1), labelMap, assignMap);
ioArgs.push_back(std::get<0>(pair));
ioArgs.push_back(std::get<1>(pair));
}
// unit (always last)
ioArgs.push_back(builder.create<mlir::ConstantOp>(
loc, builder.getIntegerAttr(ioFuncTy.getInput(ioArgs.size()),
Fortran::runtime::io::DefaultUnit)));
}
}
template <bool isInput, bool hasIOCtrl = true, typename A>
static mlir::Value
genDataTransferStmt(Fortran::lower::AbstractConverter &converter, const A &stmt,
Fortran::lower::pft::LabelEvalMap &labelMap,
Fortran::lower::pft::SymbolLabelMap &assignMap) {
auto &builder = converter.getFirOpBuilder();
auto loc = converter.getCurrentLocation();
const bool isFormatted = isDataTransferFormatted(stmt);
const bool isList = isFormatted ? isDataTransferList(stmt) : false;
const bool isIntern = isDataTransferInternal(stmt);
const bool isOtherIntern =
isIntern ? isDataTransferInternalNotDefaultKind(stmt) : false;
const bool isAsynch = isDataTransferAsynchronous(stmt);
const bool isNml = isDataTransferNamelist(stmt);
// Determine which BeginXyz call to make.
mlir::FuncOp ioFunc =
getBeginDataTransfer<isInput>(loc, builder, isFormatted, isList, isIntern,
isOtherIntern, isAsynch, isNml);
mlir::FunctionType ioFuncTy = ioFunc.getType();
// Append BeginXyz call arguments. File name and line number are always last.
llvm::SmallVector<mlir::Value, 8> ioArgs;
genBeginCallArguments<hasIOCtrl>(ioArgs, converter, loc, stmt, ioFuncTy,
isFormatted, isList, isIntern, isOtherIntern,
isAsynch, isNml, labelMap, assignMap);
ioArgs.push_back(
getDefaultFilename(builder, loc, ioFuncTy.getInput(ioArgs.size())));
ioArgs.push_back(
getDefaultLineNo(builder, loc, ioFuncTy.getInput(ioArgs.size())));
// Arguments are done; call the BeginXyz function.
mlir::Value cookie =
builder.create<mlir::CallOp>(loc, ioFunc, ioArgs).getResult(0);
// Generate an EnableHandlers call and remaining specifier calls.
ConditionSpecifierInfo csi;
mlir::OpBuilder::InsertPoint insertPt;
mlir::Value ok;
if constexpr (hasIOCtrl) {
genConditionHandlerCall(converter, loc, cookie, stmt.controls, csi);
insertPt = threadSpecs(converter, loc, cookie, stmt.controls,
csi.hasErrorConditionSpecifier(), ok);
}
// Generate data transfer list calls.
if constexpr (isInput) // ReadStmt
genInputItemList(converter, cookie, stmt.items, insertPt,
csi.hasTransferConditionSpecifier(), ok, false);
else if constexpr (std::is_same_v<A, Fortran::parser::PrintStmt>)
genOutputItemList(converter, cookie, std::get<1>(stmt.t), insertPt,
csi.hasTransferConditionSpecifier(), ok, false);
else // WriteStmt
genOutputItemList(converter, cookie, stmt.items, insertPt,
csi.hasTransferConditionSpecifier(), ok, false);
// Generate end statement call/s.
if (insertPt.isSet())
builder.restoreInsertionPoint(insertPt);
return genEndIO(converter, loc, cookie, csi);
}
void Fortran::lower::genPrintStatement(
Fortran::lower::AbstractConverter &converter,
const Fortran::parser::PrintStmt &stmt,
Fortran::lower::pft::LabelEvalMap &labelMap,
Fortran::lower::pft::SymbolLabelMap &assignMap) {
// PRINT does not take an io-control-spec. It only has a format specifier, so
// it is a simplified case of WRITE.
genDataTransferStmt</*isInput=*/false, /*ioCtrl=*/false>(converter, stmt,
labelMap, assignMap);
}
mlir::Value Fortran::lower::genWriteStatement(
Fortran::lower::AbstractConverter &converter,
const Fortran::parser::WriteStmt &stmt,
Fortran::lower::pft::LabelEvalMap &labelMap,
Fortran::lower::pft::SymbolLabelMap &assignMap) {
return genDataTransferStmt</*isInput=*/false>(converter, stmt, labelMap,
assignMap);
}
mlir::Value Fortran::lower::genReadStatement(
Fortran::lower::AbstractConverter &converter,
const Fortran::parser::ReadStmt &stmt,
Fortran::lower::pft::LabelEvalMap &labelMap,
Fortran::lower::pft::SymbolLabelMap &assignMap) {
return genDataTransferStmt</*isInput=*/true>(converter, stmt, labelMap,
assignMap);
}
/// Get the file expression from the inquire spec list. Also return if the
/// expression is a file name.
static std::pair<const Fortran::semantics::SomeExpr *, bool>
getInquireFileExpr(const std::list<Fortran::parser::InquireSpec> *stmt) {
if (!stmt)
return {nullptr, false};
for (const auto &spec : *stmt) {
if (auto *f = std::get_if<Fortran::parser::FileUnitNumber>(&spec.u))
return {Fortran::semantics::GetExpr(*f), false};
if (auto *f = std::get_if<Fortran::parser::FileNameExpr>(&spec.u))
return {Fortran::semantics::GetExpr(*f), true};
}
// semantics should have already caught this condition
llvm_unreachable("inquire spec must have a file");
}
mlir::Value Fortran::lower::genInquireStatement(
Fortran::lower::AbstractConverter &converter,
const Fortran::parser::InquireStmt &stmt) {
auto &builder = converter.getFirOpBuilder();
auto loc = converter.getCurrentLocation();
mlir::FuncOp beginFunc;
mlir::Value cookie;
ConditionSpecifierInfo csi{};
const auto *list =
std::get_if<std::list<Fortran::parser::InquireSpec>>(&stmt.u);
auto exprPair = getInquireFileExpr(list);
auto inquireFileUnit = [&]() -> bool {
return exprPair.first && !exprPair.second;
};
auto inquireFileName = [&]() -> bool {
return exprPair.first && exprPair.second;
};
// Determine which BeginInquire call to make.
if (inquireFileUnit()) {
// File unit call.
beginFunc = getIORuntimeFunc<mkIOKey(BeginInquireUnit)>(loc, builder);
mlir::FunctionType beginFuncTy = beginFunc.getType();
auto unit = converter.genExprValue(exprPair.first, loc);
auto un = builder.createConvert(loc, beginFuncTy.getInput(0), unit);
auto file = getDefaultFilename(builder, loc, beginFuncTy.getInput(1));
auto line = getDefaultLineNo(builder, loc, beginFuncTy.getInput(2));
llvm::SmallVector<mlir::Value, 4> beginArgs{un, file, line};
cookie =
builder.create<mlir::CallOp>(loc, beginFunc, beginArgs).getResult(0);
// Handle remaining arguments in specifier list.
genConditionHandlerCall(converter, loc, cookie, *list, csi);
} else if (inquireFileName()) {
// Filename call.
beginFunc = getIORuntimeFunc<mkIOKey(BeginInquireFile)>(loc, builder);
mlir::FunctionType beginFuncTy = beginFunc.getType();
auto file = converter.genExprValue(exprPair.first, loc);
// Helper to query [BUFFER, LEN].
Fortran::lower::CharacterExprHelper helper(builder, loc);
auto dataLen = helper.materializeCharacter(file);
auto buff =
builder.createConvert(loc, beginFuncTy.getInput(0), dataLen.first);
auto len =
builder.createConvert(loc, beginFuncTy.getInput(1), dataLen.second);
auto kindInt = helper.getCharacterKind(file.getType());
mlir::Value kindValue =
builder.createIntegerConstant(loc, beginFuncTy.getInput(2), kindInt);
auto sourceFile = getDefaultFilename(builder, loc, beginFuncTy.getInput(3));
auto line = getDefaultLineNo(builder, loc, beginFuncTy.getInput(4));
llvm::SmallVector<mlir::Value, 5> beginArgs = {
buff, len, kindValue, sourceFile, line,
};
cookie =
builder.create<mlir::CallOp>(loc, beginFunc, beginArgs).getResult(0);
// Handle remaining arguments in specifier list.
genConditionHandlerCall(converter, loc, cookie, *list, csi);
} else {
// Io length call.
const auto *ioLength =
std::get_if<Fortran::parser::InquireStmt::Iolength>(&stmt.u);
assert(ioLength && "must have an io length");
beginFunc = getIORuntimeFunc<mkIOKey(BeginInquireIoLength)>(loc, builder);
mlir::FunctionType beginFuncTy = beginFunc.getType();
auto file = getDefaultFilename(builder, loc, beginFuncTy.getInput(0));
auto line = getDefaultLineNo(builder, loc, beginFuncTy.getInput(1));
llvm::SmallVector<mlir::Value, 4> beginArgs{file, line};
cookie =
builder.create<mlir::CallOp>(loc, beginFunc, beginArgs).getResult(0);
// Handle remaining arguments in output list.
genConditionHandlerCall(
converter, loc, cookie,
std::get<std::list<Fortran::parser::OutputItem>>(ioLength->t), csi);
}
// Generate end statement call.
return genEndIO(converter, loc, cookie, csi);
}