1 //===-- lib/Semantics/runtime-type-info.cpp ---------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "flang/Semantics/runtime-type-info.h"
10 #include "mod-file.h"
11 #include "flang/Evaluate/fold-designator.h"
12 #include "flang/Evaluate/fold.h"
13 #include "flang/Evaluate/tools.h"
14 #include "flang/Evaluate/type.h"
15 #include "flang/Semantics/scope.h"
16 #include "flang/Semantics/tools.h"
17 #include <functional>
18 #include <list>
19 #include <map>
20 #include <string>
21 
22 namespace Fortran::semantics {
23 
24 static int FindLenParameterIndex(
25     const SymbolVector &parameters, const Symbol &symbol) {
26   int lenIndex{0};
27   for (SymbolRef ref : parameters) {
28     if (&*ref == &symbol) {
29       return lenIndex;
30     }
31     if (ref->get<TypeParamDetails>().attr() == common::TypeParamAttr::Len) {
32       ++lenIndex;
33     }
34   }
35   DIE("Length type parameter not found in parameter order");
36   return -1;
37 }
38 
39 class RuntimeTableBuilder {
40 public:
41   RuntimeTableBuilder(SemanticsContext &, RuntimeDerivedTypeTables &);
42   void DescribeTypes(Scope &scope, bool inSchemata);
43 
44 private:
45   const Symbol *DescribeType(Scope &);
46   const Symbol &GetSchemaSymbol(const char *) const;
47   const DeclTypeSpec &GetSchema(const char *) const;
48   SomeExpr GetEnumValue(const char *) const;
49   Symbol &CreateObject(const std::string &, const DeclTypeSpec &, Scope &);
50   // The names of created symbols are saved in and owned by the
51   // RuntimeDerivedTypeTables instance returned by
52   // BuildRuntimeDerivedTypeTables() so that references to those names remain
53   // valid for lowering.
54   SourceName SaveObjectName(const std::string &);
55   SomeExpr SaveNameAsPointerTarget(Scope &, const std::string &);
56   const SymbolVector *GetTypeParameters(const Symbol &);
57   evaluate::StructureConstructor DescribeComponent(const Symbol &,
58       const ObjectEntityDetails &, Scope &, Scope &,
59       const std::string &distinctName, const SymbolVector *parameters);
60   evaluate::StructureConstructor DescribeComponent(
61       const Symbol &, const ProcEntityDetails &, Scope &);
62   bool InitializeDataPointer(evaluate::StructureConstructorValues &,
63       const Symbol &symbol, const ObjectEntityDetails &object, Scope &scope,
64       Scope &dtScope, const std::string &distinctName);
65   evaluate::StructureConstructor PackageIntValue(
66       const SomeExpr &genre, std::int64_t = 0) const;
67   SomeExpr PackageIntValueExpr(const SomeExpr &genre, std::int64_t = 0) const;
68   std::vector<const Symbol *> CollectBindings(const Scope &dtScope) const;
69   std::vector<evaluate::StructureConstructor> DescribeBindings(
70       const Scope &dtScope, Scope &);
71   void DescribeGeneric(
72       const GenericDetails &, std::map<int, evaluate::StructureConstructor> &);
73   void DescribeSpecialProc(std::map<int, evaluate::StructureConstructor> &,
74       const Symbol &specificOrBinding, bool isAssignment, bool isFinal,
75       std::optional<GenericKind::DefinedIo>);
76   void IncorporateDefinedIoGenericInterfaces(
77       std::map<int, evaluate::StructureConstructor> &, SourceName,
78       GenericKind::DefinedIo, const Scope *);
79 
80   // Instantiated for ParamValue and Bound
81   template <typename A>
82   evaluate::StructureConstructor GetValue(
83       const A &x, const SymbolVector *parameters) {
84     if (x.isExplicit()) {
85       return GetValue(x.GetExplicit(), parameters);
86     } else {
87       return PackageIntValue(deferredEnum_);
88     }
89   }
90 
91   // Specialization for optional<Expr<SomeInteger and SubscriptInteger>>
92   template <typename T>
93   evaluate::StructureConstructor GetValue(
94       const std::optional<evaluate::Expr<T>> &expr,
95       const SymbolVector *parameters) {
96     if (auto constValue{evaluate::ToInt64(expr)}) {
97       return PackageIntValue(explicitEnum_, *constValue);
98     }
99     if (expr) {
100       if (parameters) {
101         if (const Symbol * lenParam{evaluate::ExtractBareLenParameter(*expr)}) {
102           return PackageIntValue(
103               lenParameterEnum_, FindLenParameterIndex(*parameters, *lenParam));
104         }
105       }
106       context_.Say(location_,
107           "Specification expression '%s' is neither constant nor a length "
108           "type parameter"_err_en_US,
109           expr->AsFortran());
110     }
111     return PackageIntValue(deferredEnum_);
112   }
113 
114   SemanticsContext &context_;
115   RuntimeDerivedTypeTables &tables_;
116   std::map<const Symbol *, SymbolVector> orderedTypeParameters_;
117   int anonymousTypes_{0};
118 
119   const DeclTypeSpec &derivedTypeSchema_; // TYPE(DerivedType)
120   const DeclTypeSpec &componentSchema_; // TYPE(Component)
121   const DeclTypeSpec &procPtrSchema_; // TYPE(ProcPtrComponent)
122   const DeclTypeSpec &valueSchema_; // TYPE(Value)
123   const DeclTypeSpec &bindingSchema_; // TYPE(Binding)
124   const DeclTypeSpec &specialSchema_; // TYPE(SpecialBinding)
125   SomeExpr deferredEnum_; // Value::Genre::Deferred
126   SomeExpr explicitEnum_; // Value::Genre::Explicit
127   SomeExpr lenParameterEnum_; // Value::Genre::LenParameter
128   SomeExpr scalarAssignmentEnum_; // SpecialBinding::Which::ScalarAssignment
129   SomeExpr
130       elementalAssignmentEnum_; // SpecialBinding::Which::ElementalAssignment
131   SomeExpr readFormattedEnum_; // SpecialBinding::Which::ReadFormatted
132   SomeExpr readUnformattedEnum_; // SpecialBinding::Which::ReadUnformatted
133   SomeExpr writeFormattedEnum_; // SpecialBinding::Which::WriteFormatted
134   SomeExpr writeUnformattedEnum_; // SpecialBinding::Which::WriteUnformatted
135   SomeExpr elementalFinalEnum_; // SpecialBinding::Which::ElementalFinal
136   SomeExpr assumedRankFinalEnum_; // SpecialBinding::Which::AssumedRankFinal
137   SomeExpr scalarFinalEnum_; // SpecialBinding::Which::ScalarFinal
138   parser::CharBlock location_;
139   std::set<const Scope *> ignoreScopes_;
140 };
141 
142 RuntimeTableBuilder::RuntimeTableBuilder(
143     SemanticsContext &c, RuntimeDerivedTypeTables &t)
144     : context_{c}, tables_{t}, derivedTypeSchema_{GetSchema("derivedtype")},
145       componentSchema_{GetSchema("component")}, procPtrSchema_{GetSchema(
146                                                     "procptrcomponent")},
147       valueSchema_{GetSchema("value")}, bindingSchema_{GetSchema("binding")},
148       specialSchema_{GetSchema("specialbinding")}, deferredEnum_{GetEnumValue(
149                                                        "deferred")},
150       explicitEnum_{GetEnumValue("explicit")}, lenParameterEnum_{GetEnumValue(
151                                                    "lenparameter")},
152       scalarAssignmentEnum_{GetEnumValue("scalarassignment")},
153       elementalAssignmentEnum_{GetEnumValue("elementalassignment")},
154       readFormattedEnum_{GetEnumValue("readformatted")},
155       readUnformattedEnum_{GetEnumValue("readunformatted")},
156       writeFormattedEnum_{GetEnumValue("writeformatted")},
157       writeUnformattedEnum_{GetEnumValue("writeunformatted")},
158       elementalFinalEnum_{GetEnumValue("elementalfinal")},
159       assumedRankFinalEnum_{GetEnumValue("assumedrankfinal")},
160       scalarFinalEnum_{GetEnumValue("scalarfinal")} {
161   ignoreScopes_.insert(tables_.schemata);
162 }
163 
164 void RuntimeTableBuilder::DescribeTypes(Scope &scope, bool inSchemata) {
165   inSchemata |= ignoreScopes_.find(&scope) != ignoreScopes_.end();
166   if (scope.IsDerivedType()) {
167     if (!inSchemata) { // don't loop trying to describe a schema
168       DescribeType(scope);
169     }
170   } else {
171     scope.InstantiateDerivedTypes();
172   }
173   for (Scope &child : scope.children()) {
174     DescribeTypes(child, inSchemata);
175   }
176 }
177 
178 // Returns derived type instantiation's parameters in declaration order
179 const SymbolVector *RuntimeTableBuilder::GetTypeParameters(
180     const Symbol &symbol) {
181   auto iter{orderedTypeParameters_.find(&symbol)};
182   if (iter != orderedTypeParameters_.end()) {
183     return &iter->second;
184   } else {
185     return &orderedTypeParameters_
186                 .emplace(&symbol, OrderParameterDeclarations(symbol))
187                 .first->second;
188   }
189 }
190 
191 static Scope &GetContainingNonDerivedScope(Scope &scope) {
192   Scope *p{&scope};
193   while (p->IsDerivedType()) {
194     p = &p->parent();
195   }
196   return *p;
197 }
198 
199 static const Symbol &GetSchemaField(
200     const DerivedTypeSpec &derived, const std::string &name) {
201   const Scope &scope{
202       DEREF(derived.scope() ? derived.scope() : derived.typeSymbol().scope())};
203   auto iter{scope.find(SourceName(name))};
204   CHECK(iter != scope.end());
205   return *iter->second;
206 }
207 
208 static const Symbol &GetSchemaField(
209     const DeclTypeSpec &derived, const std::string &name) {
210   return GetSchemaField(DEREF(derived.AsDerived()), name);
211 }
212 
213 static evaluate::StructureConstructorValues &AddValue(
214     evaluate::StructureConstructorValues &values, const DeclTypeSpec &spec,
215     const std::string &name, SomeExpr &&x) {
216   values.emplace(GetSchemaField(spec, name), std::move(x));
217   return values;
218 }
219 
220 static evaluate::StructureConstructorValues &AddValue(
221     evaluate::StructureConstructorValues &values, const DeclTypeSpec &spec,
222     const std::string &name, const SomeExpr &x) {
223   values.emplace(GetSchemaField(spec, name), x);
224   return values;
225 }
226 
227 static SomeExpr IntToExpr(std::int64_t n) {
228   return evaluate::AsGenericExpr(evaluate::ExtentExpr{n});
229 }
230 
231 static evaluate::StructureConstructor Structure(
232     const DeclTypeSpec &spec, evaluate::StructureConstructorValues &&values) {
233   return {DEREF(spec.AsDerived()), std::move(values)};
234 }
235 
236 static SomeExpr StructureExpr(evaluate::StructureConstructor &&x) {
237   return SomeExpr{evaluate::Expr<evaluate::SomeDerived>{std::move(x)}};
238 }
239 
240 static int GetIntegerKind(const Symbol &symbol) {
241   auto dyType{evaluate::DynamicType::From(symbol)};
242   CHECK(dyType && dyType->category() == TypeCategory::Integer);
243   return dyType->kind();
244 }
245 
246 // Save a rank-1 array constant of some numeric type as an
247 // initialized data object in a scope.
248 template <typename T>
249 static SomeExpr SaveNumericPointerTarget(
250     Scope &scope, SourceName name, std::vector<typename T::Scalar> &&x) {
251   if (x.empty()) {
252     return SomeExpr{evaluate::NullPointer{}};
253   } else {
254     ObjectEntityDetails object;
255     if (const auto *spec{scope.FindType(
256             DeclTypeSpec{NumericTypeSpec{T::category, KindExpr{T::kind}}})}) {
257       object.set_type(*spec);
258     } else {
259       object.set_type(scope.MakeNumericType(T::category, KindExpr{T::kind}));
260     }
261     auto elements{static_cast<evaluate::ConstantSubscript>(x.size())};
262     ArraySpec arraySpec;
263     arraySpec.push_back(ShapeSpec::MakeExplicit(Bound{0}, Bound{elements - 1}));
264     object.set_shape(arraySpec);
265     object.set_init(evaluate::AsGenericExpr(evaluate::Constant<T>{
266         std::move(x), evaluate::ConstantSubscripts{elements}}));
267     Symbol &symbol{*scope
268                         .try_emplace(name, Attrs{Attr::TARGET, Attr::SAVE},
269                             std::move(object))
270                         .first->second};
271     symbol.set(Symbol::Flag::CompilerCreated);
272     return evaluate::AsGenericExpr(
273         evaluate::Expr<T>{evaluate::Designator<T>{symbol}});
274   }
275 }
276 
277 // Save an arbitrarily shaped array constant of some derived type
278 // as an initialized data object in a scope.
279 static SomeExpr SaveDerivedPointerTarget(Scope &scope, SourceName name,
280     std::vector<evaluate::StructureConstructor> &&x,
281     evaluate::ConstantSubscripts &&shape) {
282   if (x.empty()) {
283     return SomeExpr{evaluate::NullPointer{}};
284   } else {
285     const auto &derivedType{x.front().GetType().GetDerivedTypeSpec()};
286     ObjectEntityDetails object;
287     DeclTypeSpec typeSpec{DeclTypeSpec::TypeDerived, derivedType};
288     if (const DeclTypeSpec * spec{scope.FindType(typeSpec)}) {
289       object.set_type(*spec);
290     } else {
291       object.set_type(scope.MakeDerivedType(
292           DeclTypeSpec::TypeDerived, common::Clone(derivedType)));
293     }
294     if (!shape.empty()) {
295       ArraySpec arraySpec;
296       for (auto n : shape) {
297         arraySpec.push_back(ShapeSpec::MakeExplicit(Bound{0}, Bound{n - 1}));
298       }
299       object.set_shape(arraySpec);
300     }
301     object.set_init(
302         evaluate::AsGenericExpr(evaluate::Constant<evaluate::SomeDerived>{
303             derivedType, std::move(x), std::move(shape)}));
304     Symbol &symbol{*scope
305                         .try_emplace(name, Attrs{Attr::TARGET, Attr::SAVE},
306                             std::move(object))
307                         .first->second};
308     symbol.set(Symbol::Flag::CompilerCreated);
309     return evaluate::AsGenericExpr(
310         evaluate::Designator<evaluate::SomeDerived>{symbol});
311   }
312 }
313 
314 static SomeExpr SaveObjectInit(
315     Scope &scope, SourceName name, const ObjectEntityDetails &object) {
316   Symbol &symbol{*scope
317                       .try_emplace(name, Attrs{Attr::TARGET, Attr::SAVE},
318                           ObjectEntityDetails{object})
319                       .first->second};
320   CHECK(symbol.get<ObjectEntityDetails>().init().has_value());
321   symbol.set(Symbol::Flag::CompilerCreated);
322   return evaluate::AsGenericExpr(
323       evaluate::Designator<evaluate::SomeDerived>{symbol});
324 }
325 
326 template <int KIND> static SomeExpr IntExpr(std::int64_t n) {
327   return evaluate::AsGenericExpr(
328       evaluate::Constant<evaluate::Type<TypeCategory::Integer, KIND>>{n});
329 }
330 
331 const Symbol *RuntimeTableBuilder::DescribeType(Scope &dtScope) {
332   if (const Symbol * info{dtScope.runtimeDerivedTypeDescription()}) {
333     return info;
334   }
335   const DerivedTypeSpec *derivedTypeSpec{dtScope.derivedTypeSpec()};
336   if (!derivedTypeSpec && !dtScope.IsParameterizedDerivedType() &&
337       dtScope.symbol()) {
338     // This derived type was declared (obviously, there's a Scope) but never
339     // used in this compilation (no instantiated DerivedTypeSpec points here).
340     // Create a DerivedTypeSpec now for it so that ComponentIterator
341     // will work. This covers the case of a derived type that's declared in
342     // a module but used only by clients and submodules, enabling the
343     // run-time "no initialization needed here" flag to work.
344     DerivedTypeSpec derived{dtScope.symbol()->name(), *dtScope.symbol()};
345     DeclTypeSpec &decl{
346         dtScope.MakeDerivedType(DeclTypeSpec::TypeDerived, std::move(derived))};
347     derivedTypeSpec = &decl.derivedTypeSpec();
348   }
349   const Symbol *dtSymbol{
350       derivedTypeSpec ? &derivedTypeSpec->typeSymbol() : dtScope.symbol()};
351   if (!dtSymbol) {
352     return nullptr;
353   }
354   auto locationRestorer{common::ScopedSet(location_, dtSymbol->name())};
355   // Check for an existing description that can be imported from a USE'd module
356   std::string typeName{dtSymbol->name().ToString()};
357   if (typeName.empty() || typeName[0] == '.') {
358     return nullptr;
359   }
360   std::string distinctName{typeName};
361   if (&dtScope != dtSymbol->scope()) {
362     distinctName += "."s + std::to_string(anonymousTypes_++);
363   }
364   std::string dtDescName{".dt."s + distinctName};
365   Scope &scope{GetContainingNonDerivedScope(dtScope)};
366   if (distinctName == typeName && scope.IsModule()) {
367     if (const Symbol * description{scope.FindSymbol(SourceName{dtDescName})}) {
368       dtScope.set_runtimeDerivedTypeDescription(*description);
369       return description;
370     }
371   }
372   // Create a new description object before populating it so that mutual
373   // references will work as pointer targets.
374   Symbol &dtObject{CreateObject(dtDescName, derivedTypeSchema_, scope)};
375   dtScope.set_runtimeDerivedTypeDescription(dtObject);
376   evaluate::StructureConstructorValues dtValues;
377   AddValue(dtValues, derivedTypeSchema_, "name"s,
378       SaveNameAsPointerTarget(scope, typeName));
379   bool isPDTdefinition{
380       !derivedTypeSpec && dtScope.IsParameterizedDerivedType()};
381   if (!isPDTdefinition) {
382     auto sizeInBytes{static_cast<common::ConstantSubscript>(dtScope.size())};
383     if (auto alignment{dtScope.alignment().value_or(0)}) {
384       sizeInBytes += alignment - 1;
385       sizeInBytes /= alignment;
386       sizeInBytes *= alignment;
387     }
388     AddValue(
389         dtValues, derivedTypeSchema_, "sizeinbytes"s, IntToExpr(sizeInBytes));
390   }
391   bool isPDTinstantiation{derivedTypeSpec && &dtScope != dtSymbol->scope()};
392   if (isPDTinstantiation) {
393     // is PDT instantiation
394     const Symbol *uninstDescObject{
395         DescribeType(DEREF(const_cast<Scope *>(dtSymbol->scope())))};
396     AddValue(dtValues, derivedTypeSchema_, "uninstantiated"s,
397         evaluate::AsGenericExpr(evaluate::Expr<evaluate::SomeDerived>{
398             evaluate::Designator<evaluate::SomeDerived>{
399                 DEREF(uninstDescObject)}}));
400   } else {
401     AddValue(dtValues, derivedTypeSchema_, "uninstantiated"s,
402         SomeExpr{evaluate::NullPointer{}});
403   }
404   using Int8 = evaluate::Type<TypeCategory::Integer, 8>;
405   using Int1 = evaluate::Type<TypeCategory::Integer, 1>;
406   std::vector<Int8::Scalar> kinds;
407   std::vector<Int1::Scalar> lenKinds;
408   const SymbolVector *parameters{GetTypeParameters(*dtSymbol)};
409   if (parameters) {
410     // Package the derived type's parameters in declaration order for
411     // each category of parameter.  KIND= type parameters are described
412     // by their instantiated (or default) values, while LEN= type
413     // parameters are described by their INTEGER kinds.
414     for (SymbolRef ref : *parameters) {
415       const auto &tpd{ref->get<TypeParamDetails>()};
416       if (tpd.attr() == common::TypeParamAttr::Kind) {
417         auto value{evaluate::ToInt64(tpd.init()).value_or(0)};
418         if (derivedTypeSpec) {
419           if (const auto *pv{derivedTypeSpec->FindParameter(ref->name())}) {
420             if (pv->GetExplicit()) {
421               if (auto instantiatedValue{
422                       evaluate::ToInt64(*pv->GetExplicit())}) {
423                 value = *instantiatedValue;
424               }
425             }
426           }
427         }
428         kinds.emplace_back(value);
429       } else { // LEN= parameter
430         lenKinds.emplace_back(GetIntegerKind(*ref));
431       }
432     }
433   }
434   AddValue(dtValues, derivedTypeSchema_, "kindparameter"s,
435       SaveNumericPointerTarget<Int8>(
436           scope, SaveObjectName(".kp."s + distinctName), std::move(kinds)));
437   AddValue(dtValues, derivedTypeSchema_, "lenparameterkind"s,
438       SaveNumericPointerTarget<Int1>(
439           scope, SaveObjectName(".lpk."s + distinctName), std::move(lenKinds)));
440   // Traverse the components of the derived type
441   if (!isPDTdefinition) {
442     std::vector<const Symbol *> dataComponentSymbols;
443     std::vector<evaluate::StructureConstructor> procPtrComponents;
444     std::map<int, evaluate::StructureConstructor> specials;
445     for (const auto &pair : dtScope) {
446       const Symbol &symbol{*pair.second};
447       auto locationRestorer{common::ScopedSet(location_, symbol.name())};
448       std::visit(
449           common::visitors{
450               [&](const TypeParamDetails &) {
451                 // already handled above in declaration order
452               },
453               [&](const ObjectEntityDetails &) {
454                 dataComponentSymbols.push_back(&symbol);
455               },
456               [&](const ProcEntityDetails &proc) {
457                 if (IsProcedurePointer(symbol)) {
458                   procPtrComponents.emplace_back(
459                       DescribeComponent(symbol, proc, scope));
460                 }
461               },
462               [&](const ProcBindingDetails &) { // handled in a later pass
463               },
464               [&](const GenericDetails &generic) {
465                 DescribeGeneric(generic, specials);
466               },
467               [&](const auto &) {
468                 common::die(
469                     "unexpected details on symbol '%s' in derived type scope",
470                     symbol.name().ToString().c_str());
471               },
472           },
473           symbol.details());
474     }
475     // Sort the data component symbols by offset before emitting them
476     std::sort(dataComponentSymbols.begin(), dataComponentSymbols.end(),
477         [](const Symbol *x, const Symbol *y) {
478           return x->offset() < y->offset();
479         });
480     std::vector<evaluate::StructureConstructor> dataComponents;
481     for (const Symbol *symbol : dataComponentSymbols) {
482       auto locationRestorer{common::ScopedSet(location_, symbol->name())};
483       dataComponents.emplace_back(
484           DescribeComponent(*symbol, symbol->get<ObjectEntityDetails>(), scope,
485               dtScope, distinctName, parameters));
486     }
487     AddValue(dtValues, derivedTypeSchema_, "component"s,
488         SaveDerivedPointerTarget(scope, SaveObjectName(".c."s + distinctName),
489             std::move(dataComponents),
490             evaluate::ConstantSubscripts{
491                 static_cast<evaluate::ConstantSubscript>(
492                     dataComponents.size())}));
493     AddValue(dtValues, derivedTypeSchema_, "procptr"s,
494         SaveDerivedPointerTarget(scope, SaveObjectName(".p."s + distinctName),
495             std::move(procPtrComponents),
496             evaluate::ConstantSubscripts{
497                 static_cast<evaluate::ConstantSubscript>(
498                     procPtrComponents.size())}));
499     // Compile the "vtable" of type-bound procedure bindings
500     std::vector<evaluate::StructureConstructor> bindings{
501         DescribeBindings(dtScope, scope)};
502     AddValue(dtValues, derivedTypeSchema_, "binding"s,
503         SaveDerivedPointerTarget(scope, SaveObjectName(".v."s + distinctName),
504             std::move(bindings),
505             evaluate::ConstantSubscripts{
506                 static_cast<evaluate::ConstantSubscript>(bindings.size())}));
507     // Describe "special" bindings to defined assignments, FINAL subroutines,
508     // and user-defined derived type I/O subroutines.
509     const DerivedTypeDetails &dtDetails{dtSymbol->get<DerivedTypeDetails>()};
510     for (const auto &pair : dtDetails.finals()) {
511       DescribeSpecialProc(
512           specials, *pair.second, false /*!isAssignment*/, true, std::nullopt);
513     }
514     IncorporateDefinedIoGenericInterfaces(specials,
515         SourceName{"read(formatted)", 15},
516         GenericKind::DefinedIo::ReadFormatted, &scope);
517     IncorporateDefinedIoGenericInterfaces(specials,
518         SourceName{"read(unformatted)", 17},
519         GenericKind::DefinedIo::ReadUnformatted, &scope);
520     IncorporateDefinedIoGenericInterfaces(specials,
521         SourceName{"write(formatted)", 16},
522         GenericKind::DefinedIo::WriteFormatted, &scope);
523     IncorporateDefinedIoGenericInterfaces(specials,
524         SourceName{"write(unformatted)", 18},
525         GenericKind::DefinedIo::WriteUnformatted, &scope);
526     // Pack the special procedure bindings in ascending order of their "which"
527     // code values, and compile a little-endian bit-set of those codes for
528     // use in O(1) look-up at run time.
529     std::vector<evaluate::StructureConstructor> sortedSpecials;
530     std::uint32_t specialBitSet{0};
531     for (auto &pair : specials) {
532       auto bit{std::uint32_t{1} << pair.first};
533       CHECK(!(specialBitSet & bit));
534       specialBitSet |= bit;
535       sortedSpecials.emplace_back(std::move(pair.second));
536     }
537     AddValue(dtValues, derivedTypeSchema_, "special"s,
538         SaveDerivedPointerTarget(scope, SaveObjectName(".s."s + distinctName),
539             std::move(sortedSpecials),
540             evaluate::ConstantSubscripts{
541                 static_cast<evaluate::ConstantSubscript>(specials.size())}));
542     AddValue(dtValues, derivedTypeSchema_, "specialbitset"s,
543         IntExpr<4>(specialBitSet));
544     // Note the presence/absence of a parent component
545     AddValue(dtValues, derivedTypeSchema_, "hasparent"s,
546         IntExpr<1>(dtScope.GetDerivedTypeParent() != nullptr));
547     // To avoid wasting run time attempting to initialize derived type
548     // instances without any initialized components, analyze the type
549     // and set a flag if there's nothing to do for it at run time.
550     AddValue(dtValues, derivedTypeSchema_, "noinitializationneeded"s,
551         IntExpr<1>(
552             derivedTypeSpec && !derivedTypeSpec->HasDefaultInitialization()));
553     // Similarly, a flag to short-circuit destruction when not needed.
554     AddValue(dtValues, derivedTypeSchema_, "nodestructionneeded"s,
555         IntExpr<1>(derivedTypeSpec && !derivedTypeSpec->HasDestruction()));
556     // Similarly, a flag to short-circuit finalization when not needed.
557     AddValue(dtValues, derivedTypeSchema_, "nofinalizationneeded"s,
558         IntExpr<1>(derivedTypeSpec && !IsFinalizable(*derivedTypeSpec)));
559   }
560   dtObject.get<ObjectEntityDetails>().set_init(MaybeExpr{
561       StructureExpr(Structure(derivedTypeSchema_, std::move(dtValues)))});
562   return &dtObject;
563 }
564 
565 static const Symbol &GetSymbol(const Scope &schemata, SourceName name) {
566   auto iter{schemata.find(name)};
567   CHECK(iter != schemata.end());
568   const Symbol &symbol{*iter->second};
569   return symbol;
570 }
571 
572 const Symbol &RuntimeTableBuilder::GetSchemaSymbol(const char *name) const {
573   return GetSymbol(
574       DEREF(tables_.schemata), SourceName{name, std::strlen(name)});
575 }
576 
577 const DeclTypeSpec &RuntimeTableBuilder::GetSchema(
578     const char *schemaName) const {
579   Scope &schemata{DEREF(tables_.schemata)};
580   SourceName name{schemaName, std::strlen(schemaName)};
581   const Symbol &symbol{GetSymbol(schemata, name)};
582   CHECK(symbol.has<DerivedTypeDetails>());
583   CHECK(symbol.scope());
584   CHECK(symbol.scope()->IsDerivedType());
585   const DeclTypeSpec *spec{nullptr};
586   if (symbol.scope()->derivedTypeSpec()) {
587     DeclTypeSpec typeSpec{
588         DeclTypeSpec::TypeDerived, *symbol.scope()->derivedTypeSpec()};
589     spec = schemata.FindType(typeSpec);
590   }
591   if (!spec) {
592     DeclTypeSpec typeSpec{
593         DeclTypeSpec::TypeDerived, DerivedTypeSpec{name, symbol}};
594     spec = schemata.FindType(typeSpec);
595   }
596   if (!spec) {
597     spec = &schemata.MakeDerivedType(
598         DeclTypeSpec::TypeDerived, DerivedTypeSpec{name, symbol});
599   }
600   CHECK(spec->AsDerived());
601   return *spec;
602 }
603 
604 SomeExpr RuntimeTableBuilder::GetEnumValue(const char *name) const {
605   const Symbol &symbol{GetSchemaSymbol(name)};
606   auto value{evaluate::ToInt64(symbol.get<ObjectEntityDetails>().init())};
607   CHECK(value.has_value());
608   return IntExpr<1>(*value);
609 }
610 
611 Symbol &RuntimeTableBuilder::CreateObject(
612     const std::string &name, const DeclTypeSpec &type, Scope &scope) {
613   ObjectEntityDetails object;
614   object.set_type(type);
615   auto pair{scope.try_emplace(SaveObjectName(name),
616       Attrs{Attr::TARGET, Attr::SAVE}, std::move(object))};
617   CHECK(pair.second);
618   Symbol &result{*pair.first->second};
619   result.set(Symbol::Flag::CompilerCreated);
620   return result;
621 }
622 
623 SourceName RuntimeTableBuilder::SaveObjectName(const std::string &name) {
624   return *tables_.names.insert(name).first;
625 }
626 
627 SomeExpr RuntimeTableBuilder::SaveNameAsPointerTarget(
628     Scope &scope, const std::string &name) {
629   CHECK(!name.empty());
630   CHECK(name.front() != '.');
631   ObjectEntityDetails object;
632   auto len{static_cast<common::ConstantSubscript>(name.size())};
633   if (const auto *spec{scope.FindType(DeclTypeSpec{CharacterTypeSpec{
634           ParamValue{len, common::TypeParamAttr::Len}, KindExpr{1}}})}) {
635     object.set_type(*spec);
636   } else {
637     object.set_type(scope.MakeCharacterType(
638         ParamValue{len, common::TypeParamAttr::Len}, KindExpr{1}));
639   }
640   using evaluate::Ascii;
641   using AsciiExpr = evaluate::Expr<Ascii>;
642   object.set_init(evaluate::AsGenericExpr(AsciiExpr{name}));
643   Symbol &symbol{*scope
644                       .try_emplace(SaveObjectName(".n."s + name),
645                           Attrs{Attr::TARGET, Attr::SAVE}, std::move(object))
646                       .first->second};
647   symbol.set(Symbol::Flag::CompilerCreated);
648   return evaluate::AsGenericExpr(
649       AsciiExpr{evaluate::Designator<Ascii>{symbol}});
650 }
651 
652 evaluate::StructureConstructor RuntimeTableBuilder::DescribeComponent(
653     const Symbol &symbol, const ObjectEntityDetails &object, Scope &scope,
654     Scope &dtScope, const std::string &distinctName,
655     const SymbolVector *parameters) {
656   evaluate::StructureConstructorValues values;
657   auto &foldingContext{context_.foldingContext()};
658   auto typeAndShape{evaluate::characteristics::TypeAndShape::Characterize(
659       symbol, foldingContext)};
660   CHECK(typeAndShape.has_value());
661   auto dyType{typeAndShape->type()};
662   const auto &shape{typeAndShape->shape()};
663   AddValue(values, componentSchema_, "name"s,
664       SaveNameAsPointerTarget(scope, symbol.name().ToString()));
665   AddValue(values, componentSchema_, "category"s,
666       IntExpr<1>(static_cast<int>(dyType.category())));
667   if (dyType.IsUnlimitedPolymorphic() ||
668       dyType.category() == TypeCategory::Derived) {
669     AddValue(values, componentSchema_, "kind"s, IntExpr<1>(0));
670   } else {
671     AddValue(values, componentSchema_, "kind"s, IntExpr<1>(dyType.kind()));
672   }
673   AddValue(values, componentSchema_, "offset"s, IntExpr<8>(symbol.offset()));
674   // CHARACTER length
675   auto len{typeAndShape->LEN()};
676   if (const semantics::DerivedTypeSpec *
677       pdtInstance{dtScope.derivedTypeSpec()}) {
678     auto restorer{foldingContext.WithPDTInstance(*pdtInstance)};
679     len = Fold(foldingContext, std::move(len));
680   }
681   if (dyType.category() == TypeCategory::Character && len) {
682     // Ignore IDIM(x) (represented as MAX(0, x))
683     if (const auto *clamped{evaluate::UnwrapExpr<
684             evaluate::Extremum<evaluate::SubscriptInteger>>(*len)}) {
685       if (clamped->ordering == evaluate::Ordering::Greater &&
686           clamped->left() == evaluate::Expr<evaluate::SubscriptInteger>{0}) {
687         len = clamped->right();
688       }
689     }
690     AddValue(values, componentSchema_, "characterlen"s,
691         evaluate::AsGenericExpr(GetValue(len, parameters)));
692   } else {
693     AddValue(values, componentSchema_, "characterlen"s,
694         PackageIntValueExpr(deferredEnum_));
695   }
696   // Describe component's derived type
697   std::vector<evaluate::StructureConstructor> lenParams;
698   if (dyType.category() == TypeCategory::Derived &&
699       !dyType.IsUnlimitedPolymorphic()) {
700     const DerivedTypeSpec &spec{dyType.GetDerivedTypeSpec()};
701     Scope *derivedScope{const_cast<Scope *>(
702         spec.scope() ? spec.scope() : spec.typeSymbol().scope())};
703     const Symbol *derivedDescription{DescribeType(DEREF(derivedScope))};
704     AddValue(values, componentSchema_, "derived"s,
705         evaluate::AsGenericExpr(evaluate::Expr<evaluate::SomeDerived>{
706             evaluate::Designator<evaluate::SomeDerived>{
707                 DEREF(derivedDescription)}}));
708     // Package values of LEN parameters, if any
709     if (const SymbolVector * specParams{GetTypeParameters(spec.typeSymbol())}) {
710       for (SymbolRef ref : *specParams) {
711         const auto &tpd{ref->get<TypeParamDetails>()};
712         if (tpd.attr() == common::TypeParamAttr::Len) {
713           if (const ParamValue * paramValue{spec.FindParameter(ref->name())}) {
714             lenParams.emplace_back(GetValue(*paramValue, parameters));
715           } else {
716             lenParams.emplace_back(GetValue(tpd.init(), parameters));
717           }
718         }
719       }
720     }
721   } else {
722     // Subtle: a category of Derived with a null derived type pointer
723     // signifies CLASS(*)
724     AddValue(values, componentSchema_, "derived"s,
725         SomeExpr{evaluate::NullPointer{}});
726   }
727   // LEN type parameter values for the component's type
728   if (!lenParams.empty()) {
729     AddValue(values, componentSchema_, "lenvalue"s,
730         SaveDerivedPointerTarget(scope,
731             SaveObjectName(
732                 ".lv."s + distinctName + "."s + symbol.name().ToString()),
733             std::move(lenParams),
734             evaluate::ConstantSubscripts{
735                 static_cast<evaluate::ConstantSubscript>(lenParams.size())}));
736   } else {
737     AddValue(values, componentSchema_, "lenvalue"s,
738         SomeExpr{evaluate::NullPointer{}});
739   }
740   // Shape information
741   int rank{evaluate::GetRank(shape)};
742   AddValue(values, componentSchema_, "rank"s, IntExpr<1>(rank));
743   if (rank > 0 && !IsAllocatable(symbol) && !IsPointer(symbol)) {
744     std::vector<evaluate::StructureConstructor> bounds;
745     evaluate::NamedEntity entity{symbol};
746     for (int j{0}; j < rank; ++j) {
747       bounds.emplace_back(GetValue(std::make_optional(evaluate::GetLowerBound(
748                                        foldingContext, entity, j)),
749           parameters));
750       bounds.emplace_back(GetValue(
751           evaluate::GetUpperBound(foldingContext, entity, j), parameters));
752     }
753     AddValue(values, componentSchema_, "bounds"s,
754         SaveDerivedPointerTarget(scope,
755             SaveObjectName(
756                 ".b."s + distinctName + "."s + symbol.name().ToString()),
757             std::move(bounds), evaluate::ConstantSubscripts{2, rank}));
758   } else {
759     AddValue(
760         values, componentSchema_, "bounds"s, SomeExpr{evaluate::NullPointer{}});
761   }
762   // Default component initialization
763   bool hasDataInit{false};
764   if (IsAllocatable(symbol)) {
765     AddValue(values, componentSchema_, "genre"s, GetEnumValue("allocatable"));
766   } else if (IsPointer(symbol)) {
767     AddValue(values, componentSchema_, "genre"s, GetEnumValue("pointer"));
768     hasDataInit = InitializeDataPointer(
769         values, symbol, object, scope, dtScope, distinctName);
770   } else if (IsAutomatic(symbol)) {
771     AddValue(values, componentSchema_, "genre"s, GetEnumValue("automatic"));
772   } else {
773     AddValue(values, componentSchema_, "genre"s, GetEnumValue("data"));
774     hasDataInit = object.init().has_value();
775     if (hasDataInit) {
776       AddValue(values, componentSchema_, "initialization"s,
777           SaveObjectInit(scope,
778               SaveObjectName(
779                   ".di."s + distinctName + "."s + symbol.name().ToString()),
780               object));
781     }
782   }
783   if (!hasDataInit) {
784     AddValue(values, componentSchema_, "initialization"s,
785         SomeExpr{evaluate::NullPointer{}});
786   }
787   return {DEREF(componentSchema_.AsDerived()), std::move(values)};
788 }
789 
790 evaluate::StructureConstructor RuntimeTableBuilder::DescribeComponent(
791     const Symbol &symbol, const ProcEntityDetails &proc, Scope &scope) {
792   evaluate::StructureConstructorValues values;
793   AddValue(values, procPtrSchema_, "name"s,
794       SaveNameAsPointerTarget(scope, symbol.name().ToString()));
795   AddValue(values, procPtrSchema_, "offset"s, IntExpr<8>(symbol.offset()));
796   if (auto init{proc.init()}; init && *init) {
797     AddValue(values, procPtrSchema_, "initialization"s,
798         SomeExpr{evaluate::ProcedureDesignator{**init}});
799   } else {
800     AddValue(values, procPtrSchema_, "initialization"s,
801         SomeExpr{evaluate::NullPointer{}});
802   }
803   return {DEREF(procPtrSchema_.AsDerived()), std::move(values)};
804 }
805 
806 // Create a static pointer object with the same initialization
807 // from whence the runtime can memcpy() the data pointer
808 // component initialization.
809 // Creates and interconnects the symbols, scopes, and types for
810 //   TYPE :: ptrDt
811 //     type, POINTER :: name
812 //   END TYPE
813 //   TYPE(ptrDt), TARGET, SAVE :: ptrInit = ptrDt(designator)
814 // and then initializes the original component by setting
815 //   initialization = ptrInit
816 // which takes the address of ptrInit because the type is C_PTR.
817 // This technique of wrapping the data pointer component into
818 // a derived type instance disables any reason for lowering to
819 // attempt to dereference the RHS of an initializer, thereby
820 // allowing the runtime to actually perform the initialization
821 // by means of a simple memcpy() of the wrapped descriptor in
822 // ptrInit to the data pointer component being initialized.
823 bool RuntimeTableBuilder::InitializeDataPointer(
824     evaluate::StructureConstructorValues &values, const Symbol &symbol,
825     const ObjectEntityDetails &object, Scope &scope, Scope &dtScope,
826     const std::string &distinctName) {
827   if (object.init().has_value()) {
828     SourceName ptrDtName{SaveObjectName(
829         ".dp."s + distinctName + "."s + symbol.name().ToString())};
830     Symbol &ptrDtSym{
831         *scope.try_emplace(ptrDtName, Attrs{}, UnknownDetails{}).first->second};
832     ptrDtSym.set(Symbol::Flag::CompilerCreated);
833     Scope &ptrDtScope{scope.MakeScope(Scope::Kind::DerivedType, &ptrDtSym)};
834     ignoreScopes_.insert(&ptrDtScope);
835     ObjectEntityDetails ptrDtObj;
836     ptrDtObj.set_type(DEREF(object.type()));
837     ptrDtObj.set_shape(object.shape());
838     Symbol &ptrDtComp{*ptrDtScope
839                            .try_emplace(symbol.name(), Attrs{Attr::POINTER},
840                                std::move(ptrDtObj))
841                            .first->second};
842     DerivedTypeDetails ptrDtDetails;
843     ptrDtDetails.add_component(ptrDtComp);
844     ptrDtSym.set_details(std::move(ptrDtDetails));
845     ptrDtSym.set_scope(&ptrDtScope);
846     DeclTypeSpec &ptrDtDeclType{
847         scope.MakeDerivedType(DeclTypeSpec::Category::TypeDerived,
848             DerivedTypeSpec{ptrDtName, ptrDtSym})};
849     DerivedTypeSpec &ptrDtDerived{DEREF(ptrDtDeclType.AsDerived())};
850     ptrDtDerived.set_scope(ptrDtScope);
851     ptrDtDerived.CookParameters(context_.foldingContext());
852     ptrDtDerived.Instantiate(scope);
853     ObjectEntityDetails ptrInitObj;
854     ptrInitObj.set_type(ptrDtDeclType);
855     evaluate::StructureConstructorValues ptrInitValues;
856     AddValue(
857         ptrInitValues, ptrDtDeclType, symbol.name().ToString(), *object.init());
858     ptrInitObj.set_init(evaluate::AsGenericExpr(
859         Structure(ptrDtDeclType, std::move(ptrInitValues))));
860     AddValue(values, componentSchema_, "initialization"s,
861         SaveObjectInit(scope,
862             SaveObjectName(
863                 ".di."s + distinctName + "."s + symbol.name().ToString()),
864             ptrInitObj));
865     return true;
866   } else {
867     return false;
868   }
869 }
870 
871 evaluate::StructureConstructor RuntimeTableBuilder::PackageIntValue(
872     const SomeExpr &genre, std::int64_t n) const {
873   evaluate::StructureConstructorValues xs;
874   AddValue(xs, valueSchema_, "genre"s, genre);
875   AddValue(xs, valueSchema_, "value"s, IntToExpr(n));
876   return Structure(valueSchema_, std::move(xs));
877 }
878 
879 SomeExpr RuntimeTableBuilder::PackageIntValueExpr(
880     const SomeExpr &genre, std::int64_t n) const {
881   return StructureExpr(PackageIntValue(genre, n));
882 }
883 
884 std::vector<const Symbol *> RuntimeTableBuilder::CollectBindings(
885     const Scope &dtScope) const {
886   std::vector<const Symbol *> result;
887   std::map<SourceName, const Symbol *> localBindings;
888   // Collect local bindings
889   for (auto pair : dtScope) {
890     const Symbol &symbol{*pair.second};
891     if (symbol.has<ProcBindingDetails>()) {
892       localBindings.emplace(symbol.name(), &symbol);
893     }
894   }
895   if (const Scope * parentScope{dtScope.GetDerivedTypeParent()}) {
896     result = CollectBindings(*parentScope);
897     // Apply overrides from the local bindings of the extended type
898     for (auto iter{result.begin()}; iter != result.end(); ++iter) {
899       const Symbol &symbol{**iter};
900       auto overridden{localBindings.find(symbol.name())};
901       if (overridden != localBindings.end()) {
902         *iter = overridden->second;
903         localBindings.erase(overridden);
904       }
905     }
906   }
907   // Add remaining (non-overriding) local bindings in name order to the result
908   for (auto pair : localBindings) {
909     result.push_back(pair.second);
910   }
911   return result;
912 }
913 
914 std::vector<evaluate::StructureConstructor>
915 RuntimeTableBuilder::DescribeBindings(const Scope &dtScope, Scope &scope) {
916   std::vector<evaluate::StructureConstructor> result;
917   for (const Symbol *symbol : CollectBindings(dtScope)) {
918     evaluate::StructureConstructorValues values;
919     AddValue(values, bindingSchema_, "proc"s,
920         SomeExpr{evaluate::ProcedureDesignator{
921             symbol->get<ProcBindingDetails>().symbol()}});
922     AddValue(values, bindingSchema_, "name"s,
923         SaveNameAsPointerTarget(scope, symbol->name().ToString()));
924     result.emplace_back(DEREF(bindingSchema_.AsDerived()), std::move(values));
925   }
926   return result;
927 }
928 
929 void RuntimeTableBuilder::DescribeGeneric(const GenericDetails &generic,
930     std::map<int, evaluate::StructureConstructor> &specials) {
931   std::visit(common::visitors{
932                  [&](const GenericKind::OtherKind &k) {
933                    if (k == GenericKind::OtherKind::Assignment) {
934                      for (auto ref : generic.specificProcs()) {
935                        DescribeSpecialProc(specials, *ref, true,
936                            false /*!final*/, std::nullopt);
937                      }
938                    }
939                  },
940                  [&](const GenericKind::DefinedIo &io) {
941                    switch (io) {
942                    case GenericKind::DefinedIo::ReadFormatted:
943                    case GenericKind::DefinedIo::ReadUnformatted:
944                    case GenericKind::DefinedIo::WriteFormatted:
945                    case GenericKind::DefinedIo::WriteUnformatted:
946                      for (auto ref : generic.specificProcs()) {
947                        DescribeSpecialProc(
948                            specials, *ref, false, false /*!final*/, io);
949                      }
950                      break;
951                    }
952                  },
953                  [](const auto &) {},
954              },
955       generic.kind().u);
956 }
957 
958 void RuntimeTableBuilder::DescribeSpecialProc(
959     std::map<int, evaluate::StructureConstructor> &specials,
960     const Symbol &specificOrBinding, bool isAssignment, bool isFinal,
961     std::optional<GenericKind::DefinedIo> io) {
962   const auto *binding{specificOrBinding.detailsIf<ProcBindingDetails>()};
963   const Symbol &specific{*(binding ? &binding->symbol() : &specificOrBinding)};
964   if (auto proc{evaluate::characteristics::Procedure::Characterize(
965           specific, context_.foldingContext())}) {
966     std::uint8_t isArgDescriptorSet{0};
967     int argThatMightBeDescriptor{0};
968     MaybeExpr which;
969     if (isAssignment) {
970       // Only type-bound asst's with the same type on both dummy arguments
971       // are germane to the runtime, which needs only these to implement
972       // component assignment as part of intrinsic assignment.
973       // Non-type-bound generic INTERFACEs and assignments from distinct
974       // types must not be used for component intrinsic assignment.
975       CHECK(proc->dummyArguments.size() == 2);
976       const auto t1{
977           DEREF(std::get_if<evaluate::characteristics::DummyDataObject>(
978                     &proc->dummyArguments[0].u))
979               .type.type()};
980       const auto t2{
981           DEREF(std::get_if<evaluate::characteristics::DummyDataObject>(
982                     &proc->dummyArguments[1].u))
983               .type.type()};
984       if (!binding || t1.category() != TypeCategory::Derived ||
985           t2.category() != TypeCategory::Derived ||
986           t1.IsUnlimitedPolymorphic() || t2.IsUnlimitedPolymorphic() ||
987           t1.GetDerivedTypeSpec() != t2.GetDerivedTypeSpec()) {
988         return;
989       }
990       which = proc->IsElemental() ? elementalAssignmentEnum_
991                                   : scalarAssignmentEnum_;
992       if (binding && binding->passName() &&
993           *binding->passName() == proc->dummyArguments[1].name) {
994         argThatMightBeDescriptor = 1;
995         isArgDescriptorSet |= 2;
996       } else {
997         argThatMightBeDescriptor = 2; // the non-passed-object argument
998         isArgDescriptorSet |= 1;
999       }
1000     } else if (isFinal) {
1001       CHECK(binding == nullptr); // FINALs are not bindings
1002       CHECK(proc->dummyArguments.size() == 1);
1003       if (proc->IsElemental()) {
1004         which = elementalFinalEnum_;
1005       } else {
1006         const auto &typeAndShape{
1007             std::get<evaluate::characteristics::DummyDataObject>(
1008                 proc->dummyArguments.at(0).u)
1009                 .type};
1010         if (typeAndShape.attrs().test(
1011                 evaluate::characteristics::TypeAndShape::Attr::AssumedRank)) {
1012           which = assumedRankFinalEnum_;
1013           isArgDescriptorSet |= 1;
1014         } else {
1015           which = scalarFinalEnum_;
1016           if (int rank{evaluate::GetRank(typeAndShape.shape())}; rank > 0) {
1017             argThatMightBeDescriptor = 1;
1018             which = IntExpr<1>(ToInt64(which).value() + rank);
1019           }
1020         }
1021       }
1022     } else { // user defined derived type I/O
1023       CHECK(proc->dummyArguments.size() >= 4);
1024       if (binding) {
1025         isArgDescriptorSet |= 1;
1026       }
1027       switch (io.value()) {
1028       case GenericKind::DefinedIo::ReadFormatted:
1029         which = readFormattedEnum_;
1030         break;
1031       case GenericKind::DefinedIo::ReadUnformatted:
1032         which = readUnformattedEnum_;
1033         break;
1034       case GenericKind::DefinedIo::WriteFormatted:
1035         which = writeFormattedEnum_;
1036         break;
1037       case GenericKind::DefinedIo::WriteUnformatted:
1038         which = writeUnformattedEnum_;
1039         break;
1040       }
1041     }
1042     if (argThatMightBeDescriptor != 0 &&
1043         !proc->dummyArguments.at(argThatMightBeDescriptor - 1)
1044              .CanBePassedViaImplicitInterface()) {
1045       isArgDescriptorSet |= 1 << (argThatMightBeDescriptor - 1);
1046     }
1047     evaluate::StructureConstructorValues values;
1048     auto index{evaluate::ToInt64(which)};
1049     CHECK(index.has_value());
1050     AddValue(
1051         values, specialSchema_, "which"s, SomeExpr{std::move(which.value())});
1052     AddValue(values, specialSchema_, "isargdescriptorset"s,
1053         IntExpr<1>(isArgDescriptorSet));
1054     AddValue(values, specialSchema_, "proc"s,
1055         SomeExpr{evaluate::ProcedureDesignator{specific}});
1056     auto pair{specials.try_emplace(
1057         *index, DEREF(specialSchema_.AsDerived()), std::move(values))};
1058     CHECK(pair.second); // ensure not already present
1059   }
1060 }
1061 
1062 void RuntimeTableBuilder::IncorporateDefinedIoGenericInterfaces(
1063     std::map<int, evaluate::StructureConstructor> &specials, SourceName name,
1064     GenericKind::DefinedIo definedIo, const Scope *scope) {
1065   for (; !scope->IsGlobal(); scope = &scope->parent()) {
1066     if (auto asst{scope->find(name)}; asst != scope->end()) {
1067       const Symbol &generic{*asst->second};
1068       const auto &genericDetails{generic.get<GenericDetails>()};
1069       CHECK(std::holds_alternative<GenericKind::DefinedIo>(
1070           genericDetails.kind().u));
1071       CHECK(std::get<GenericKind::DefinedIo>(genericDetails.kind().u) ==
1072           definedIo);
1073       for (auto ref : genericDetails.specificProcs()) {
1074         DescribeSpecialProc(specials, *ref, false, false, definedIo);
1075       }
1076     }
1077   }
1078 }
1079 
1080 RuntimeDerivedTypeTables BuildRuntimeDerivedTypeTables(
1081     SemanticsContext &context) {
1082   RuntimeDerivedTypeTables result;
1083   result.schemata = context.GetBuiltinModule("__fortran_type_info");
1084   if (result.schemata) {
1085     RuntimeTableBuilder builder{context, result};
1086     builder.DescribeTypes(context.globalScope(), false);
1087   }
1088   return result;
1089 }
1090 } // namespace Fortran::semantics
1091