-
Notifications
You must be signed in to change notification settings - Fork 13.3k
/
Copy pathIO.cpp
2537 lines (2411 loc) · 117 KB
/
IO.cpp
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
//===-- IO.cpp -- IO 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
//
//===----------------------------------------------------------------------===//
//
// Coding style: https://mlir.llvm.org/getting_started/DeveloperGuide/
//
//===----------------------------------------------------------------------===//
#include "flang/Lower/IO.h"
#include "flang/Common/uint128.h"
#include "flang/Evaluate/tools.h"
#include "flang/Lower/Allocatable.h"
#include "flang/Lower/Bridge.h"
#include "flang/Lower/CallInterface.h"
#include "flang/Lower/ConvertExpr.h"
#include "flang/Lower/ConvertVariable.h"
#include "flang/Lower/Mangler.h"
#include "flang/Lower/PFTBuilder.h"
#include "flang/Lower/Runtime.h"
#include "flang/Lower/StatementContext.h"
#include "flang/Lower/Support/Utils.h"
#include "flang/Lower/VectorSubscripts.h"
#include "flang/Optimizer/Builder/Character.h"
#include "flang/Optimizer/Builder/Complex.h"
#include "flang/Optimizer/Builder/FIRBuilder.h"
#include "flang/Optimizer/Builder/Runtime/RTBuilder.h"
#include "flang/Optimizer/Builder/Runtime/Stop.h"
#include "flang/Optimizer/Builder/Todo.h"
#include "flang/Optimizer/Dialect/FIRDialect.h"
#include "flang/Optimizer/Dialect/Support/FIRContext.h"
#include "flang/Optimizer/Support/InternalNames.h"
#include "flang/Parser/parse-tree.h"
#include "flang/Runtime/io-api.h"
#include "flang/Semantics/runtime-type-info.h"
#include "flang/Semantics/tools.h"
#include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h"
#include "llvm/Support/Debug.h"
#include <optional>
#define DEBUG_TYPE "flang-lower-io"
using namespace Fortran::runtime::io;
#define mkIOKey(X) FirmkKey(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(BeginBackspace), mkIOKey(BeginClose), mkIOKey(BeginEndfile),
mkIOKey(BeginExternalFormattedInput), mkIOKey(BeginExternalFormattedOutput),
mkIOKey(BeginExternalListInput), mkIOKey(BeginExternalListOutput),
mkIOKey(BeginFlush), mkIOKey(BeginInquireFile),
mkIOKey(BeginInquireIoLength), mkIOKey(BeginInquireUnit),
mkIOKey(BeginInternalArrayFormattedInput),
mkIOKey(BeginInternalArrayFormattedOutput),
mkIOKey(BeginInternalArrayListInput), mkIOKey(BeginInternalArrayListOutput),
mkIOKey(BeginInternalFormattedInput), mkIOKey(BeginInternalFormattedOutput),
mkIOKey(BeginInternalListInput), mkIOKey(BeginInternalListOutput),
mkIOKey(BeginOpenNewUnit), mkIOKey(BeginOpenUnit), mkIOKey(BeginRewind),
mkIOKey(BeginUnformattedInput), mkIOKey(BeginUnformattedOutput),
mkIOKey(BeginWait), mkIOKey(BeginWaitAll),
mkIOKey(CheckUnitNumberInRange64), mkIOKey(CheckUnitNumberInRange128),
mkIOKey(EnableHandlers), mkIOKey(EndIoStatement),
mkIOKey(GetAsynchronousId), mkIOKey(GetIoLength), mkIOKey(GetIoMsg),
mkIOKey(GetNewUnit), mkIOKey(GetSize), mkIOKey(InputAscii),
mkIOKey(InputComplex32), mkIOKey(InputComplex64), mkIOKey(InputDerivedType),
mkIOKey(InputDescriptor), mkIOKey(InputInteger), mkIOKey(InputLogical),
mkIOKey(InputNamelist), mkIOKey(InputReal32), mkIOKey(InputReal64),
mkIOKey(InquireCharacter), mkIOKey(InquireInteger64),
mkIOKey(InquireLogical), mkIOKey(InquirePendingId), mkIOKey(OutputAscii),
mkIOKey(OutputComplex32), mkIOKey(OutputComplex64),
mkIOKey(OutputDerivedType), mkIOKey(OutputDescriptor),
mkIOKey(OutputInteger8), mkIOKey(OutputInteger16), mkIOKey(OutputInteger32),
mkIOKey(OutputInteger64), mkIOKey(OutputInteger128), mkIOKey(OutputLogical),
mkIOKey(OutputNamelist), mkIOKey(OutputReal32), mkIOKey(OutputReal64),
mkIOKey(SetAccess), mkIOKey(SetAction), mkIOKey(SetAdvance),
mkIOKey(SetAsynchronous), mkIOKey(SetBlank), mkIOKey(SetCarriagecontrol),
mkIOKey(SetConvert), mkIOKey(SetDecimal), mkIOKey(SetDelim),
mkIOKey(SetEncoding), mkIOKey(SetFile), mkIOKey(SetForm), mkIOKey(SetPad),
mkIOKey(SetPos), mkIOKey(SetPosition), mkIOKey(SetRec), mkIOKey(SetRecl),
mkIOKey(SetRound), mkIOKey(SetSign), mkIOKey(SetStatus)>
newIOTable;
} // namespace Fortran::lower
namespace {
/// IO statements may require exceptional condition handling. A statement that
/// encounters an exceptional condition may branch to a label given on an ERR
/// (error), END (end-of-file), or EOR (end-of-record) specifier. An IOSTAT
/// specifier variable may be set to a value that indicates some condition,
/// and an IOMSG specifier variable may be set to a description of a condition.
struct ConditionSpecInfo {
const Fortran::lower::SomeExpr *ioStatExpr{};
std::optional<fir::ExtendedValue> ioMsg;
bool hasErr{};
bool hasEnd{};
bool hasEor{};
fir::IfOp bigUnitIfOp;
/// Check for any condition specifier that applies to specifier processing.
bool hasErrorConditionSpec() 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 hasTransferConditionSpec() const {
return hasErrorConditionSpec() || hasEnd || hasEor;
}
/// Check for any condition specifier, including IOMSG.
bool hasAnyConditionSpec() const {
return hasTransferConditionSpec() || ioMsg;
}
};
} // namespace
template <typename D>
static void genIoLoop(Fortran::lower::AbstractConverter &converter,
mlir::Value cookie, const D &ioImpliedDo,
bool isFormatted, bool checkResult, mlir::Value &ok,
bool inLoop);
/// 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>(Fortran::lower::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 fir::runtime::FuncTypeBuilderFunc getTypeModel() {
return std::get<A>(Fortran::lower::newIOTable).getTypeModel();
}
inline int64_t getLength(mlir::Type argTy) {
return mlir::cast<fir::SequenceType>(argTy).getShape()[0];
}
/// 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,
ConditionSpecInfo &csi,
Fortran::lower::StatementContext &stmtCtx) {
fir::FirOpBuilder &builder = converter.getFirOpBuilder();
if (csi.ioMsg) {
mlir::func::FuncOp getIoMsg =
fir::runtime::getIORuntimeFunc<mkIOKey(GetIoMsg)>(loc, builder);
builder.create<fir::CallOp>(
loc, getIoMsg,
mlir::ValueRange{
cookie,
builder.createConvert(loc, getIoMsg.getFunctionType().getInput(1),
fir::getBase(*csi.ioMsg)),
builder.createConvert(loc, getIoMsg.getFunctionType().getInput(2),
fir::getLen(*csi.ioMsg))});
}
mlir::func::FuncOp endIoStatement =
fir::runtime::getIORuntimeFunc<mkIOKey(EndIoStatement)>(loc, builder);
auto call = builder.create<fir::CallOp>(loc, endIoStatement,
mlir::ValueRange{cookie});
mlir::Value iostat = call.getResult(0);
if (csi.bigUnitIfOp) {
stmtCtx.finalizeAndPop();
builder.create<fir::ResultOp>(loc, iostat);
builder.setInsertionPointAfter(csi.bigUnitIfOp);
iostat = csi.bigUnitIfOp.getResult(0);
}
if (csi.ioStatExpr) {
mlir::Value ioStatVar =
fir::getBase(converter.genExprAddr(loc, csi.ioStatExpr, stmtCtx));
mlir::Value ioStatResult =
builder.createConvert(loc, converter.genType(*csi.ioStatExpr), iostat);
builder.create<fir::StoreOp>(loc, ioStatResult, ioStatVar);
}
return csi.hasTransferConditionSpec() ? iostat : 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 IO
/// statement will be skipped. This may generate branch heavy, deeply nested
/// conditionals for IO statements with a large number of suboperations.
static void makeNextConditionalOn(fir::FirOpBuilder &builder,
mlir::Location loc, bool checkResult,
mlir::Value ok, bool inLoop = false) {
if (!checkResult || !ok)
// Either no IO calls need to be checked, or this will be the first call.
return;
// A previous IO 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 as an extra ifOp result. (The propagation is done in genIoLoop.)
mlir::TypeRange resTy;
// TypeRange does not own its contents, so make sure the the type object
// is live until the end of the function.
mlir::IntegerType boolTy = builder.getI1Type();
if (inLoop)
resTy = boolTy;
auto ifOp = builder.create<fir::IfOp>(loc, resTy, ok,
/*withElseRegion=*/inLoop);
builder.setInsertionPointToStart(&ifOp.getThenRegion().front());
}
// Derived type symbols may each be mapped to up to 4 defined IO procedures.
using DefinedIoProcMap = std::multimap<const Fortran::semantics::Symbol *,
Fortran::semantics::NonTbpDefinedIo>;
/// Get the current scope's non-type-bound defined IO procedures.
static DefinedIoProcMap
getDefinedIoProcMap(Fortran::lower::AbstractConverter &converter) {
const Fortran::semantics::Scope *scope = &converter.getCurrentScope();
for (; !scope->IsGlobal(); scope = &scope->parent())
if (scope->kind() == Fortran::semantics::Scope::Kind::MainProgram ||
scope->kind() == Fortran::semantics::Scope::Kind::Subprogram ||
scope->kind() == Fortran::semantics::Scope::Kind::BlockConstruct)
break;
return Fortran::semantics::CollectNonTbpDefinedIoGenericInterfaces(*scope,
false);
}
/// Check a set of defined IO procedures for any procedure pointer or dummy
/// procedures.
static bool hasLocalDefinedIoProc(DefinedIoProcMap &definedIoProcMap) {
for (auto &iface : definedIoProcMap) {
const Fortran::semantics::Symbol *procSym = iface.second.subroutine;
if (!procSym)
continue;
procSym = &procSym->GetUltimate();
if (Fortran::semantics::IsProcedurePointer(*procSym) ||
Fortran::semantics::IsDummy(*procSym))
return true;
}
return false;
}
/// Retrieve or generate a runtime description of the non-type-bound defined
/// IO procedures in the current scope. If any procedure is a dummy or a
/// procedure pointer, the result is local. Otherwise the result is static.
/// If there are no procedures, return a scope-independent default table with
/// an empty procedure list, but with the `ignoreNonTbpEntries` flag set. The
/// form of the description is defined in runtime header file non-tbp-dio.h.
static mlir::Value
getNonTbpDefinedIoTableAddr(Fortran::lower::AbstractConverter &converter,
DefinedIoProcMap &definedIoProcMap) {
fir::FirOpBuilder &builder = converter.getFirOpBuilder();
mlir::MLIRContext *context = builder.getContext();
mlir::Location loc = converter.getCurrentLocation();
mlir::Type refTy = fir::ReferenceType::get(mlir::NoneType::get(context));
std::string suffix = ".nonTbpDefinedIoTable";
std::string tableMangleName =
definedIoProcMap.empty()
? fir::NameUniquer::doGenerated("default" + suffix)
: converter.mangleName(suffix);
if (auto table = builder.getNamedGlobal(tableMangleName))
return builder.createConvert(
loc, refTy,
builder.create<fir::AddrOfOp>(loc, table.resultType(),
table.getSymbol()));
mlir::StringAttr linkOnce = builder.createLinkOnceLinkage();
mlir::Type idxTy = builder.getIndexType();
mlir::Type sizeTy =
fir::runtime::getModel<std::size_t>()(builder.getContext());
mlir::Type intTy = fir::runtime::getModel<int>()(builder.getContext());
mlir::Type boolTy = fir::runtime::getModel<bool>()(builder.getContext());
mlir::Type listTy = fir::SequenceType::get(
definedIoProcMap.size(),
mlir::TupleType::get(context, {refTy, refTy, intTy, boolTy}));
mlir::Type tableTy = mlir::TupleType::get(
context, {sizeTy, fir::ReferenceType::get(listTy), boolTy});
// Define the list of NonTbpDefinedIo procedures.
bool tableIsLocal =
!definedIoProcMap.empty() && hasLocalDefinedIoProc(definedIoProcMap);
mlir::Value listAddr =
tableIsLocal ? builder.create<fir::AllocaOp>(loc, listTy) : mlir::Value{};
std::string listMangleName = tableMangleName + ".list";
auto listFunc = [&](fir::FirOpBuilder &builder) {
mlir::Value list = builder.create<fir::UndefOp>(loc, listTy);
mlir::IntegerAttr intAttr[4];
for (int i = 0; i < 4; ++i)
intAttr[i] = builder.getIntegerAttr(idxTy, i);
llvm::SmallVector<mlir::Attribute, 2> idx = {mlir::Attribute{},
mlir::Attribute{}};
int n0 = 0, n1;
auto insert = [&](mlir::Value val) {
idx[1] = intAttr[n1++];
list = builder.create<fir::InsertValueOp>(loc, listTy, list, val,
builder.getArrayAttr(idx));
};
for (auto &iface : definedIoProcMap) {
idx[0] = builder.getIntegerAttr(idxTy, n0++);
n1 = 0;
// derived type description [const typeInfo::DerivedType &derivedType]
const Fortran::semantics::Symbol &dtSym = iface.first->GetUltimate();
std::string dtName = converter.mangleName(dtSym);
insert(builder.createConvert(
loc, refTy,
builder.create<fir::AddrOfOp>(
loc, fir::ReferenceType::get(converter.genType(dtSym)),
builder.getSymbolRefAttr(dtName))));
// defined IO procedure [void (*subroutine)()], may be null
const Fortran::semantics::Symbol *procSym = iface.second.subroutine;
if (procSym) {
procSym = &procSym->GetUltimate();
if (Fortran::semantics::IsProcedurePointer(*procSym)) {
TODO(loc, "defined IO procedure pointers");
} else if (Fortran::semantics::IsDummy(*procSym)) {
Fortran::lower::StatementContext stmtCtx;
insert(builder.create<fir::BoxAddrOp>(
loc, refTy,
fir::getBase(converter.genExprAddr(
loc,
Fortran::lower::SomeExpr{
Fortran::evaluate::ProcedureDesignator{*procSym}},
stmtCtx))));
} else {
mlir::func::FuncOp procDef = Fortran::lower::getOrDeclareFunction(
Fortran::evaluate::ProcedureDesignator{*procSym}, converter);
mlir::SymbolRefAttr nameAttr =
builder.getSymbolRefAttr(procDef.getSymName());
insert(builder.createConvert(
loc, refTy,
builder.create<fir::AddrOfOp>(loc, procDef.getFunctionType(),
nameAttr)));
}
} else {
insert(builder.createNullConstant(loc, refTy));
}
// defined IO variant, one of (read/write, formatted/unformatted)
// [common::DefinedIo definedIo]
insert(builder.createIntegerConstant(
loc, intTy, static_cast<int>(iface.second.definedIo)));
// polymorphic flag is set if first defined IO dummy arg is CLASS(T)
// [bool isDtvArgPolymorphic]
insert(builder.createIntegerConstant(loc, boolTy,
iface.second.isDtvArgPolymorphic));
}
if (tableIsLocal)
builder.create<fir::StoreOp>(loc, list, listAddr);
else
builder.create<fir::HasValueOp>(loc, list);
};
if (!definedIoProcMap.empty()) {
if (tableIsLocal)
listFunc(builder);
else
builder.createGlobalConstant(loc, listTy, listMangleName, listFunc,
linkOnce);
}
// Define the NonTbpDefinedIoTable.
mlir::Value tableAddr = tableIsLocal
? builder.create<fir::AllocaOp>(loc, tableTy)
: mlir::Value{};
auto tableFunc = [&](fir::FirOpBuilder &builder) {
mlir::Value table = builder.create<fir::UndefOp>(loc, tableTy);
// list item count [std::size_t items]
table = builder.create<fir::InsertValueOp>(
loc, tableTy, table,
builder.createIntegerConstant(loc, sizeTy, definedIoProcMap.size()),
builder.getArrayAttr(builder.getIntegerAttr(idxTy, 0)));
// item list [const NonTbpDefinedIo *item]
if (definedIoProcMap.empty())
listAddr = builder.createNullConstant(loc, builder.getRefType(listTy));
else if (fir::GlobalOp list = builder.getNamedGlobal(listMangleName))
listAddr = builder.create<fir::AddrOfOp>(loc, list.resultType(),
list.getSymbol());
assert(listAddr && "missing namelist object list");
table = builder.create<fir::InsertValueOp>(
loc, tableTy, table, listAddr,
builder.getArrayAttr(builder.getIntegerAttr(idxTy, 1)));
// [bool ignoreNonTbpEntries] conservatively set to true
table = builder.create<fir::InsertValueOp>(
loc, tableTy, table, builder.createIntegerConstant(loc, boolTy, true),
builder.getArrayAttr(builder.getIntegerAttr(idxTy, 2)));
if (tableIsLocal)
builder.create<fir::StoreOp>(loc, table, tableAddr);
else
builder.create<fir::HasValueOp>(loc, table);
};
if (tableIsLocal) {
tableFunc(builder);
} else {
fir::GlobalOp table = builder.createGlobal(
loc, tableTy, tableMangleName,
/*isConst=*/true, /*isTarget=*/false, tableFunc, linkOnce);
tableAddr = builder.create<fir::AddrOfOp>(
loc, fir::ReferenceType::get(tableTy), table.getSymbol());
}
assert(tableAddr && "missing NonTbpDefinedIo table result");
return builder.createConvert(loc, refTy, tableAddr);
}
static mlir::Value
getNonTbpDefinedIoTableAddr(Fortran::lower::AbstractConverter &converter) {
DefinedIoProcMap definedIoProcMap = getDefinedIoProcMap(converter);
return getNonTbpDefinedIoTableAddr(converter, definedIoProcMap);
}
/// Retrieve or generate a runtime description of NAMELIST group \p symbol.
/// The form of the description is defined in runtime header file namelist.h.
/// Static descriptors are generated for global objects; local descriptors for
/// local objects. If all descriptors and defined IO procedures are static,
/// the NamelistGroup is static.
static mlir::Value
getNamelistGroup(Fortran::lower::AbstractConverter &converter,
const Fortran::semantics::Symbol &symbol,
Fortran::lower::StatementContext &stmtCtx) {
fir::FirOpBuilder &builder = converter.getFirOpBuilder();
mlir::Location loc = converter.getCurrentLocation();
std::string groupMangleName = converter.mangleName(symbol);
if (auto group = builder.getNamedGlobal(groupMangleName))
return builder.create<fir::AddrOfOp>(loc, group.resultType(),
group.getSymbol());
const auto &details =
symbol.GetUltimate().get<Fortran::semantics::NamelistDetails>();
mlir::MLIRContext *context = builder.getContext();
mlir::StringAttr linkOnce = builder.createLinkOnceLinkage();
mlir::Type idxTy = builder.getIndexType();
mlir::Type sizeTy =
fir::runtime::getModel<std::size_t>()(builder.getContext());
mlir::Type charRefTy = fir::ReferenceType::get(builder.getIntegerType(8));
mlir::Type descRefTy =
fir::ReferenceType::get(fir::BoxType::get(mlir::NoneType::get(context)));
mlir::Type listTy = fir::SequenceType::get(
details.objects().size(),
mlir::TupleType::get(context, {charRefTy, descRefTy}));
mlir::Type groupTy = mlir::TupleType::get(
context, {charRefTy, sizeTy, fir::ReferenceType::get(listTy),
fir::ReferenceType::get(mlir::NoneType::get(context))});
auto stringAddress = [&](const Fortran::semantics::Symbol &symbol) {
return fir::factory::createStringLiteral(builder, loc,
symbol.name().ToString() + '\0');
};
// Define variable names, and static descriptors for global variables.
DefinedIoProcMap definedIoProcMap = getDefinedIoProcMap(converter);
bool groupIsLocal = hasLocalDefinedIoProc(definedIoProcMap);
stringAddress(symbol);
for (const Fortran::semantics::Symbol &s : details.objects()) {
stringAddress(s);
if (!Fortran::lower::symbolIsGlobal(s)) {
groupIsLocal = true;
continue;
}
// A global pointer or allocatable variable has a descriptor for typical
// accesses. Variables in multiple namelist groups may already have one.
// Create descriptors for other cases.
if (!IsAllocatableOrObjectPointer(&s)) {
std::string mangleName =
Fortran::lower::mangle::globalNamelistDescriptorName(s);
if (builder.getNamedGlobal(mangleName))
continue;
const auto expr = Fortran::evaluate::AsGenericExpr(s);
fir::BoxType boxTy =
fir::BoxType::get(fir::PointerType::get(converter.genType(s)));
auto descFunc = [&](fir::FirOpBuilder &b) {
auto box = Fortran::lower::genInitialDataTarget(
converter, loc, boxTy, *expr, /*couldBeInEquivalence=*/true);
b.create<fir::HasValueOp>(loc, box);
};
builder.createGlobalConstant(loc, boxTy, mangleName, descFunc, linkOnce);
}
}
// Define the list of Items.
mlir::Value listAddr =
groupIsLocal ? builder.create<fir::AllocaOp>(loc, listTy) : mlir::Value{};
std::string listMangleName = groupMangleName + ".list";
auto listFunc = [&](fir::FirOpBuilder &builder) {
mlir::Value list = builder.create<fir::UndefOp>(loc, listTy);
mlir::IntegerAttr zero = builder.getIntegerAttr(idxTy, 0);
mlir::IntegerAttr one = builder.getIntegerAttr(idxTy, 1);
llvm::SmallVector<mlir::Attribute, 2> idx = {mlir::Attribute{},
mlir::Attribute{}};
int n = 0;
for (const Fortran::semantics::Symbol &s : details.objects()) {
idx[0] = builder.getIntegerAttr(idxTy, n++);
idx[1] = zero;
mlir::Value nameAddr =
builder.createConvert(loc, charRefTy, fir::getBase(stringAddress(s)));
list = builder.create<fir::InsertValueOp>(loc, listTy, list, nameAddr,
builder.getArrayAttr(idx));
idx[1] = one;
mlir::Value descAddr;
if (auto desc = builder.getNamedGlobal(
Fortran::lower::mangle::globalNamelistDescriptorName(s))) {
descAddr = builder.create<fir::AddrOfOp>(loc, desc.resultType(),
desc.getSymbol());
} else if (Fortran::semantics::FindCommonBlockContaining(s) &&
IsAllocatableOrPointer(s)) {
mlir::Type symType = converter.genType(s);
const Fortran::semantics::Symbol *commonBlockSym =
Fortran::semantics::FindCommonBlockContaining(s);
std::string commonBlockName = converter.mangleName(*commonBlockSym);
fir::GlobalOp commonGlobal = builder.getNamedGlobal(commonBlockName);
mlir::Value commonBlockAddr = builder.create<fir::AddrOfOp>(
loc, commonGlobal.resultType(), commonGlobal.getSymbol());
mlir::IntegerType i8Ty = builder.getIntegerType(8);
mlir::Type i8Ptr = builder.getRefType(i8Ty);
mlir::Type seqTy = builder.getRefType(builder.getVarLenSeqTy(i8Ty));
mlir::Value base = builder.createConvert(loc, seqTy, commonBlockAddr);
std::size_t byteOffset = s.GetUltimate().offset();
mlir::Value offs = builder.createIntegerConstant(
loc, builder.getIndexType(), byteOffset);
mlir::Value varAddr = builder.create<fir::CoordinateOp>(
loc, i8Ptr, base, mlir::ValueRange{offs});
descAddr =
builder.createConvert(loc, builder.getRefType(symType), varAddr);
} else {
const auto expr = Fortran::evaluate::AsGenericExpr(s);
fir::ExtendedValue exv = converter.genExprAddr(*expr, stmtCtx);
mlir::Type type = fir::getBase(exv).getType();
if (mlir::Type baseTy = fir::dyn_cast_ptrOrBoxEleTy(type))
type = baseTy;
fir::BoxType boxType = fir::BoxType::get(fir::PointerType::get(type));
descAddr = builder.createTemporary(loc, boxType);
fir::MutableBoxValue box = fir::MutableBoxValue(descAddr, {}, {});
fir::factory::associateMutableBox(builder, loc, box, exv,
/*lbounds=*/std::nullopt);
}
descAddr = builder.createConvert(loc, descRefTy, descAddr);
list = builder.create<fir::InsertValueOp>(loc, listTy, list, descAddr,
builder.getArrayAttr(idx));
}
if (groupIsLocal)
builder.create<fir::StoreOp>(loc, list, listAddr);
else
builder.create<fir::HasValueOp>(loc, list);
};
if (groupIsLocal)
listFunc(builder);
else
builder.createGlobalConstant(loc, listTy, listMangleName, listFunc,
linkOnce);
// Define the group.
mlir::Value groupAddr = groupIsLocal
? builder.create<fir::AllocaOp>(loc, groupTy)
: mlir::Value{};
auto groupFunc = [&](fir::FirOpBuilder &builder) {
mlir::Value group = builder.create<fir::UndefOp>(loc, groupTy);
// group name [const char *groupName]
group = builder.create<fir::InsertValueOp>(
loc, groupTy, group,
builder.createConvert(loc, charRefTy,
fir::getBase(stringAddress(symbol))),
builder.getArrayAttr(builder.getIntegerAttr(idxTy, 0)));
// list item count [std::size_t items]
group = builder.create<fir::InsertValueOp>(
loc, groupTy, group,
builder.createIntegerConstant(loc, sizeTy, details.objects().size()),
builder.getArrayAttr(builder.getIntegerAttr(idxTy, 1)));
// item list [const Item *item]
if (fir::GlobalOp list = builder.getNamedGlobal(listMangleName))
listAddr = builder.create<fir::AddrOfOp>(loc, list.resultType(),
list.getSymbol());
assert(listAddr && "missing namelist object list");
group = builder.create<fir::InsertValueOp>(
loc, groupTy, group, listAddr,
builder.getArrayAttr(builder.getIntegerAttr(idxTy, 2)));
// non-type-bound defined IO procedures
// [const NonTbpDefinedIoTable *nonTbpDefinedIo]
group = builder.create<fir::InsertValueOp>(
loc, groupTy, group,
getNonTbpDefinedIoTableAddr(converter, definedIoProcMap),
builder.getArrayAttr(builder.getIntegerAttr(idxTy, 3)));
if (groupIsLocal)
builder.create<fir::StoreOp>(loc, group, groupAddr);
else
builder.create<fir::HasValueOp>(loc, group);
};
if (groupIsLocal) {
groupFunc(builder);
} else {
fir::GlobalOp group = builder.createGlobal(
loc, groupTy, groupMangleName,
/*isConst=*/true, /*isTarget=*/false, groupFunc, linkOnce);
groupAddr = builder.create<fir::AddrOfOp>(loc, group.resultType(),
group.getSymbol());
}
assert(groupAddr && "missing namelist group result");
return groupAddr;
}
/// Generate a namelist IO call.
static void genNamelistIO(Fortran::lower::AbstractConverter &converter,
mlir::Value cookie, mlir::func::FuncOp funcOp,
Fortran::semantics::Symbol &symbol, bool checkResult,
mlir::Value &ok,
Fortran::lower::StatementContext &stmtCtx) {
fir::FirOpBuilder &builder = converter.getFirOpBuilder();
mlir::Location loc = converter.getCurrentLocation();
makeNextConditionalOn(builder, loc, checkResult, ok);
mlir::Type argType = funcOp.getFunctionType().getInput(1);
mlir::Value groupAddr =
getNamelistGroup(converter, symbol.GetUltimate(), stmtCtx);
groupAddr = builder.createConvert(loc, argType, groupAddr);
llvm::SmallVector<mlir::Value> args = {cookie, groupAddr};
ok = builder.create<fir::CallOp>(loc, funcOp, args).getResult(0);
}
/// Is \p type a derived type or an array of derived type?
static bool containsDerivedType(mlir::Type type) {
mlir::Type argTy = fir::unwrapPassByRefType(fir::unwrapRefType(type));
if (mlir::isa<fir::RecordType>(argTy))
return true;
if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(argTy))
if (mlir::isa<fir::RecordType>(seqTy.getEleTy()))
return true;
return false;
}
/// Get the output function to call for a value of the given type.
static mlir::func::FuncOp getOutputFunc(mlir::Location loc,
fir::FirOpBuilder &builder,
mlir::Type type, bool isFormatted) {
if (containsDerivedType(type))
return fir::runtime::getIORuntimeFunc<mkIOKey(OutputDerivedType)>(loc,
builder);
if (!isFormatted)
return fir::runtime::getIORuntimeFunc<mkIOKey(OutputDescriptor)>(loc,
builder);
if (auto ty = mlir::dyn_cast<mlir::IntegerType>(type)) {
if (!ty.isUnsigned()) {
switch (ty.getWidth()) {
case 1:
return fir::runtime::getIORuntimeFunc<mkIOKey(OutputLogical)>(loc,
builder);
case 8:
return fir::runtime::getIORuntimeFunc<mkIOKey(OutputInteger8)>(loc,
builder);
case 16:
return fir::runtime::getIORuntimeFunc<mkIOKey(OutputInteger16)>(
loc, builder);
case 32:
return fir::runtime::getIORuntimeFunc<mkIOKey(OutputInteger32)>(
loc, builder);
case 64:
return fir::runtime::getIORuntimeFunc<mkIOKey(OutputInteger64)>(
loc, builder);
case 128:
return fir::runtime::getIORuntimeFunc<mkIOKey(OutputInteger128)>(
loc, builder);
}
llvm_unreachable("unknown OutputInteger kind");
}
}
if (auto ty = mlir::dyn_cast<mlir::FloatType>(type)) {
if (auto width = ty.getWidth(); width == 32)
return fir::runtime::getIORuntimeFunc<mkIOKey(OutputReal32)>(loc,
builder);
else if (width == 64)
return fir::runtime::getIORuntimeFunc<mkIOKey(OutputReal64)>(loc,
builder);
}
auto kindMap = fir::getKindMapping(builder.getModule());
if (auto ty = mlir::dyn_cast<mlir::ComplexType>(type)) {
// COMPLEX(KIND=k) corresponds to a pair of REAL(KIND=k).
auto width = mlir::cast<mlir::FloatType>(ty.getElementType()).getWidth();
if (width == 32)
return fir::runtime::getIORuntimeFunc<mkIOKey(OutputComplex32)>(loc,
builder);
else if (width == 64)
return fir::runtime::getIORuntimeFunc<mkIOKey(OutputComplex64)>(loc,
builder);
}
if (mlir::isa<fir::LogicalType>(type))
return fir::runtime::getIORuntimeFunc<mkIOKey(OutputLogical)>(loc, builder);
if (fir::factory::CharacterExprHelper::isCharacterScalar(type)) {
// TODO: What would it mean if the default CHARACTER KIND is set to a wide
// character encoding scheme? How do we handle UTF-8? Is it a distinct KIND
// value? For now, assume that if the default CHARACTER KIND is 8 bit,
// then it is an ASCII string and UTF-8 is unsupported.
auto asciiKind = kindMap.defaultCharacterKind();
if (kindMap.getCharacterBitsize(asciiKind) == 8 &&
fir::factory::CharacterExprHelper::getCharacterKind(type) == asciiKind)
return fir::runtime::getIORuntimeFunc<mkIOKey(OutputAscii)>(loc, builder);
}
return fir::runtime::getIORuntimeFunc<mkIOKey(OutputDescriptor)>(loc,
builder);
}
/// 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, bool isFormatted,
bool checkResult, mlir::Value &ok, bool inLoop) {
fir::FirOpBuilder &builder = converter.getFirOpBuilder();
for (const Fortran::parser::OutputItem &item : items) {
if (const auto &impliedDo = std::get_if<1>(&item.u)) {
genIoLoop(converter, cookie, impliedDo->value(), isFormatted, checkResult,
ok, inLoop);
continue;
}
auto &pExpr = std::get<Fortran::parser::Expr>(item.u);
mlir::Location loc = converter.genLocation(pExpr.source);
makeNextConditionalOn(builder, loc, checkResult, ok, inLoop);
Fortran::lower::StatementContext stmtCtx;
const auto *expr = Fortran::semantics::GetExpr(pExpr);
if (!expr)
fir::emitFatalError(loc, "internal error: could not get evaluate::Expr");
mlir::Type itemTy = converter.genType(*expr);
mlir::func::FuncOp outputFunc =
getOutputFunc(loc, builder, itemTy, isFormatted);
mlir::Type argType = outputFunc.getFunctionType().getInput(1);
assert((isFormatted || mlir::isa<fir::BoxType>(argType)) &&
"expect descriptor for unformatted IO runtime");
llvm::SmallVector<mlir::Value> outputFuncArgs = {cookie};
fir::factory::CharacterExprHelper helper{builder, loc};
if (mlir::isa<fir::BoxType>(argType)) {
mlir::Value box = fir::getBase(converter.genExprBox(loc, *expr, stmtCtx));
outputFuncArgs.push_back(
builder.createConvertWithVolatileCast(loc, argType, box));
if (containsDerivedType(itemTy))
outputFuncArgs.push_back(getNonTbpDefinedIoTableAddr(converter));
} else if (helper.isCharacterScalar(itemTy)) {
fir::ExtendedValue exv = converter.genExprAddr(loc, expr, stmtCtx);
// scalar allocatable/pointer may also get here, not clear if
// genExprAddr will lower them as CharBoxValue or BoxValue.
if (!exv.getCharBox())
llvm::report_fatal_error(
"internal error: scalar character not in CharBox");
outputFuncArgs.push_back(builder.createConvertWithVolatileCast(
loc, outputFunc.getFunctionType().getInput(1), fir::getBase(exv)));
outputFuncArgs.push_back(builder.createConvertWithVolatileCast(
loc, outputFunc.getFunctionType().getInput(2), fir::getLen(exv)));
} else {
fir::ExtendedValue itemBox = converter.genExprValue(loc, expr, stmtCtx);
mlir::Value itemValue = fir::getBase(itemBox);
if (fir::isa_complex(itemTy)) {
auto parts =
fir::factory::Complex{builder, loc}.extractParts(itemValue);
outputFuncArgs.push_back(parts.first);
outputFuncArgs.push_back(parts.second);
} else {
itemValue =
builder.createConvertWithVolatileCast(loc, argType, itemValue);
outputFuncArgs.push_back(itemValue);
}
}
ok = builder.create<fir::CallOp>(loc, outputFunc, outputFuncArgs)
.getResult(0);
}
}
/// Get the input function to call for a value of the given type.
static mlir::func::FuncOp getInputFunc(mlir::Location loc,
fir::FirOpBuilder &builder,
mlir::Type type, bool isFormatted) {
if (containsDerivedType(type))
return fir::runtime::getIORuntimeFunc<mkIOKey(InputDerivedType)>(loc,
builder);
if (!isFormatted)
return fir::runtime::getIORuntimeFunc<mkIOKey(InputDescriptor)>(loc,
builder);
if (auto ty = mlir::dyn_cast<mlir::IntegerType>(type)) {
if (type.isUnsignedInteger())
return fir::runtime::getIORuntimeFunc<mkIOKey(InputDescriptor)>(loc,
builder);
return ty.getWidth() == 1
? fir::runtime::getIORuntimeFunc<mkIOKey(InputLogical)>(loc,
builder)
: fir::runtime::getIORuntimeFunc<mkIOKey(InputInteger)>(loc,
builder);
}
if (auto ty = mlir::dyn_cast<mlir::FloatType>(type)) {
if (auto width = ty.getWidth(); width == 32)
return fir::runtime::getIORuntimeFunc<mkIOKey(InputReal32)>(loc, builder);
else if (width == 64)
return fir::runtime::getIORuntimeFunc<mkIOKey(InputReal64)>(loc, builder);
}
auto kindMap = fir::getKindMapping(builder.getModule());
if (auto ty = mlir::dyn_cast<mlir::ComplexType>(type)) {
auto width = mlir::cast<mlir::FloatType>(ty.getElementType()).getWidth();
if (width == 32)
return fir::runtime::getIORuntimeFunc<mkIOKey(InputComplex32)>(loc,
builder);
else if (width == 64)
return fir::runtime::getIORuntimeFunc<mkIOKey(InputComplex64)>(loc,
builder);
}
if (mlir::isa<fir::LogicalType>(type))
return fir::runtime::getIORuntimeFunc<mkIOKey(InputLogical)>(loc, builder);
if (fir::factory::CharacterExprHelper::isCharacterScalar(type)) {
auto asciiKind = kindMap.defaultCharacterKind();
if (kindMap.getCharacterBitsize(asciiKind) == 8 &&
fir::factory::CharacterExprHelper::getCharacterKind(type) == asciiKind)
return fir::runtime::getIORuntimeFunc<mkIOKey(InputAscii)>(loc, builder);
}
return fir::runtime::getIORuntimeFunc<mkIOKey(InputDescriptor)>(loc, builder);
}
/// Interpret the lowest byte of a LOGICAL and store that value into the full
/// storage of the LOGICAL. The load, convert, and store effectively (sign or
/// zero) extends the lowest byte into the full LOGICAL value storage, as the
/// runtime is unaware of the LOGICAL value's actual bit width (it was passed
/// as a `bool&` to the runtime in order to be set).
static void boolRefToLogical(mlir::Location loc, fir::FirOpBuilder &builder,
mlir::Value addr) {
auto boolType = builder.getRefType(builder.getI1Type());
auto boolAddr = builder.createConvert(loc, boolType, addr);
auto boolValue = builder.create<fir::LoadOp>(loc, boolAddr);
auto logicalType = fir::unwrapPassByRefType(addr.getType());
// The convert avoid making any assumptions about how LOGICALs are actually
// represented (it might end-up being either a signed or zero extension).
auto logicalValue = builder.createConvert(loc, logicalType, boolValue);
builder.create<fir::StoreOp>(loc, logicalValue, addr);
}
static mlir::Value
createIoRuntimeCallForItem(Fortran::lower::AbstractConverter &converter,
mlir::Location loc, mlir::func::FuncOp inputFunc,
mlir::Value cookie, const fir::ExtendedValue &item) {
fir::FirOpBuilder &builder = converter.getFirOpBuilder();
mlir::Type argType = inputFunc.getFunctionType().getInput(1);
llvm::SmallVector<mlir::Value> inputFuncArgs = {cookie};
if (mlir::isa<fir::BaseBoxType>(argType)) {
mlir::Value box = fir::getBase(item);
auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(box.getType());
assert(boxTy && "must be previously emboxed");
auto casted = builder.createConvertWithVolatileCast(loc, argType, box);
inputFuncArgs.push_back(casted);
if (containsDerivedType(boxTy))
inputFuncArgs.push_back(getNonTbpDefinedIoTableAddr(converter));
} else {
mlir::Value itemAddr = fir::getBase(item);
mlir::Type itemTy = fir::unwrapPassByRefType(itemAddr.getType());
inputFuncArgs.push_back(builder.createConvert(loc, argType, itemAddr));
fir::factory::CharacterExprHelper charHelper{builder, loc};
if (charHelper.isCharacterScalar(itemTy)) {
mlir::Value len = fir::getLen(item);
inputFuncArgs.push_back(builder.createConvert(
loc, inputFunc.getFunctionType().getInput(2), len));
} else if (mlir::isa<mlir::IntegerType>(itemTy)) {
inputFuncArgs.push_back(builder.create<mlir::arith::ConstantOp>(
loc, builder.getI32IntegerAttr(
mlir::cast<mlir::IntegerType>(itemTy).getWidth() / 8)));
}
}
auto call = builder.create<fir::CallOp>(loc, inputFunc, inputFuncArgs);
auto itemAddr = fir::getBase(item);
auto itemTy = fir::unwrapRefType(itemAddr.getType());
if (mlir::isa<fir::LogicalType>(itemTy))
boolRefToLogical(loc, builder, itemAddr);
return call.getResult(0);
}
/// 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,
bool isFormatted, bool checkResult,
mlir::Value &ok, bool inLoop) {
fir::FirOpBuilder &builder = converter.getFirOpBuilder();
for (const Fortran::parser::InputItem &item : items) {
if (const auto &impliedDo = std::get_if<1>(&item.u)) {
genIoLoop(converter, cookie, impliedDo->value(), isFormatted, checkResult,
ok, inLoop);
continue;
}
auto &pVar = std::get<Fortran::parser::Variable>(item.u);
mlir::Location loc = converter.genLocation(pVar.GetSource());
makeNextConditionalOn(builder, loc, checkResult, ok, inLoop);
Fortran::lower::StatementContext stmtCtx;
const auto *expr = Fortran::semantics::GetExpr(pVar);
if (!expr)
fir::emitFatalError(loc, "internal error: could not get evaluate::Expr");
if (Fortran::evaluate::HasVectorSubscript(*expr)) {
auto vectorSubscriptBox =
Fortran::lower::genVectorSubscriptBox(loc, converter, stmtCtx, *expr);
mlir::func::FuncOp inputFunc = getInputFunc(
loc, builder, vectorSubscriptBox.getElementType(), isFormatted);
const bool mustBox =
mlir::isa<fir::BoxType>(inputFunc.getFunctionType().getInput(1));
if (!checkResult) {
auto elementalGenerator = [&](const fir::ExtendedValue &element) {
createIoRuntimeCallForItem(converter, loc, inputFunc, cookie,
mustBox ? builder.createBox(loc, element)
: element);
};
vectorSubscriptBox.loopOverElements(builder, loc, elementalGenerator);
} else {
auto elementalGenerator =
[&](const fir::ExtendedValue &element) -> mlir::Value {
return createIoRuntimeCallForItem(
converter, loc, inputFunc, cookie,
mustBox ? builder.createBox(loc, element) : element);
};
if (!ok)
ok = builder.createBool(loc, true);
ok = vectorSubscriptBox.loopOverElementsWhile(builder, loc,
elementalGenerator, ok);
}
continue;
}
mlir::Type itemTy = converter.genType(*expr);
mlir::func::FuncOp inputFunc =
getInputFunc(loc, builder, itemTy, isFormatted);
auto itemExv =
mlir::isa<fir::BoxType>(inputFunc.getFunctionType().getInput(1))
? converter.genExprBox(loc, *expr, stmtCtx)
: converter.genExprAddr(loc, expr, stmtCtx);
ok = createIoRuntimeCallForItem(converter, loc, inputFunc, cookie, itemExv);
}
}
/// Generate an io-implied-do loop.
template <typename D>
static void genIoLoop(Fortran::lower::AbstractConverter &converter,
mlir::Value cookie, const D &ioImpliedDo,
bool isFormatted, bool checkResult, mlir::Value &ok,
bool inLoop) {
Fortran::lower::StatementContext stmtCtx;
fir::FirOpBuilder &builder = converter.getFirOpBuilder();
mlir::Location loc = converter.getCurrentLocation();
mlir::arith::IntegerOverflowFlags flags{};
if (!converter.getLoweringOptions().getIntegerWrapAround())
flags = bitEnumSet(flags, mlir::arith::IntegerOverflowFlags::nsw);
auto iofAttr =
mlir::arith::IntegerOverflowFlagsAttr::get(builder.getContext(), flags);
makeNextConditionalOn(builder, loc, checkResult, ok, inLoop);
const auto &itemList = std::get<0>(ioImpliedDo.t);
const auto &control = std::get<1>(ioImpliedDo.t);
const auto &loopSym = *control.name.thing.thing.symbol;
mlir::Value loopVar = fir::getBase(converter.genExprAddr(
Fortran::evaluate::AsGenericExpr(loopSym).value(), stmtCtx));
auto genControlValue = [&](const Fortran::parser::ScalarIntExpr &expr) {
mlir::Value v = fir::getBase(
converter.genExprValue(*Fortran::semantics::GetExpr(expr), stmtCtx));
return builder.createConvert(loc, builder.getIndexType(), v);
};
mlir::Value lowerValue = genControlValue(control.lower);
mlir::Value upperValue = genControlValue(control.upper);
mlir::Value stepValue =
control.step.has_value()
? genControlValue(*control.step)
: builder.create<mlir::arith::ConstantIndexOp>(loc, 1);
auto genItemList = [&](const D &ioImpliedDo) {
if constexpr (std::is_same_v<D, Fortran::parser::InputImpliedDo>)
genInputItemList(converter, cookie, itemList, isFormatted, checkResult,
ok, /*inLoop=*/true);
else
genOutputItemList(converter, cookie, itemList, isFormatted, checkResult,
ok, /*inLoop=*/true);
};
if (!checkResult) {
// No IO call result checks - the loop is a fir.do_loop op.
auto doLoopOp = builder.create<fir::DoLoopOp>(
loc, lowerValue, upperValue, stepValue, /*unordered=*/false,
/*finalCountValue=*/true);
builder.setInsertionPointToStart(doLoopOp.getBody());
mlir::Value lcv = builder.createConvert(
loc, fir::unwrapRefType(loopVar.getType()), doLoopOp.getInductionVar());
builder.create<fir::StoreOp>(loc, lcv, loopVar);
genItemList(ioImpliedDo);
builder.setInsertionPointToEnd(doLoopOp.getBody());
mlir::Value result = builder.create<mlir::arith::AddIOp>(
loc, doLoopOp.getInductionVar(), doLoopOp.getStep(), iofAttr);
builder.create<fir::ResultOp>(loc, result);
builder.setInsertionPointAfter(doLoopOp);
// The loop control variable may be used after the loop.
lcv = builder.createConvert(loc, fir::unwrapRefType(loopVar.getType()),
doLoopOp.getResult(0));
builder.create<fir::StoreOp>(loc, lcv, loopVar);
return;
}
// Check IO call results - the loop is a fir.iterate_while op.
if (!ok)
ok = builder.createBool(loc, true);
auto iterWhileOp = builder.create<fir::IterWhileOp>(
loc, lowerValue, upperValue, stepValue, ok, /*finalCountValue*/ true);
builder.setInsertionPointToStart(iterWhileOp.getBody());
mlir::Value lcv =
builder.createConvert(loc, fir::unwrapRefType(loopVar.getType()),
iterWhileOp.getInductionVar());
builder.create<fir::StoreOp>(loc, lcv, loopVar);
ok = iterWhileOp.getIterateVar();
mlir::Value falseValue =
builder.createIntegerConstant(loc, builder.getI1Type(), 0);
genItemList(ioImpliedDo);
// Unwind nested IO call scopes, filling in true and false ResultOp's.
for (mlir::Operation *op = builder.getBlock()->getParentOp();
mlir::isa<fir::IfOp>(op); op = op->getBlock()->getParentOp()) {
auto ifOp = mlir::dyn_cast<fir::IfOp>(op);
mlir::Operation *lastOp = &ifOp.getThenRegion().front().back();
builder.setInsertionPointAfter(lastOp);
// The primary ifOp result is the result of an IO call or loop.
if (mlir::isa<fir::CallOp, fir::IfOp>(*lastOp))
builder.create<fir::ResultOp>(loc, lastOp->getResult(0));