1 //===-- lib/Semantics/data-to-inits.cpp -----------------------------------===//
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 // DATA statement object/value checking and conversion to static
10 // initializers
11 // - Applies specific checks to each scalar element initialization with a
12 //   constant value or pointer target with class DataInitializationCompiler;
13 // - Collects the elemental initializations for each symbol and converts them
14 //   into a single init() expression with member function
15 //   DataChecker::ConstructInitializer().
16 
17 #include "data-to-inits.h"
18 #include "pointer-assignment.h"
19 #include "flang/Evaluate/fold-designator.h"
20 #include "flang/Evaluate/tools.h"
21 #include "flang/Semantics/tools.h"
22 
23 // The job of generating explicit static initializers for objects that don't
24 // have them in order to implement default component initialization is now being
25 // done in lowering, so don't do it here in semantics; but the code remains here
26 // in case we change our minds.
27 static constexpr bool makeDefaultInitializationExplicit{false};
28 
29 // Whether to delete the original "init()" initializers from storage-associated
30 // objects and pointers.
31 static constexpr bool removeOriginalInits{false};
32 
33 namespace Fortran::semantics {
34 
35 // Steps through a list of values in a DATA statement set; implements
36 // repetition.
37 template <typename DSV = parser::DataStmtValue> class ValueListIterator {
38 public:
39   ValueListIterator(SemanticsContext &context, const std::list<DSV> &list)
40       : context_{context}, end_{list.end()}, at_{list.begin()} {
41     SetRepetitionCount();
42   }
43   bool hasFatalError() const { return hasFatalError_; }
44   bool IsAtEnd() const { return at_ == end_; }
45   const SomeExpr *operator*() const { return GetExpr(context_, GetConstant()); }
46   parser::CharBlock LocateSource() const { return GetConstant().source; }
47   ValueListIterator &operator++() {
48     if (repetitionsRemaining_ > 0) {
49       --repetitionsRemaining_;
50     } else if (at_ != end_) {
51       ++at_;
52       SetRepetitionCount();
53     }
54     return *this;
55   }
56 
57 private:
58   using listIterator = typename std::list<DSV>::const_iterator;
59   void SetRepetitionCount();
60   const parser::DataStmtValue &GetValue() const {
61     return DEREF(common::Unwrap<const parser::DataStmtValue>(*at_));
62   }
63   const parser::DataStmtConstant &GetConstant() const {
64     return std::get<parser::DataStmtConstant>(GetValue().t);
65   }
66 
67   SemanticsContext &context_;
68   listIterator end_, at_;
69   ConstantSubscript repetitionsRemaining_{0};
70   bool hasFatalError_{false};
71 };
72 
73 template <typename DSV> void ValueListIterator<DSV>::SetRepetitionCount() {
74   for (repetitionsRemaining_ = 1; at_ != end_; ++at_) {
75     auto repetitions{GetValue().repetitions};
76     if (repetitions < 0) {
77       hasFatalError_ = true;
78     } else if (repetitions > 0) {
79       repetitionsRemaining_ = repetitions - 1;
80       return;
81     }
82   }
83   repetitionsRemaining_ = 0;
84 }
85 
86 // Collects all of the elemental initializations from DATA statements
87 // into a single image for each symbol that appears in any DATA.
88 // Expands the implied DO loops and array references.
89 // Applies checks that validate each distinct elemental initialization
90 // of the variables in a data-stmt-set, as well as those that apply
91 // to the corresponding values being used to initialize each element.
92 template <typename DSV = parser::DataStmtValue>
93 class DataInitializationCompiler {
94 public:
95   DataInitializationCompiler(DataInitializations &inits,
96       evaluate::ExpressionAnalyzer &a, const std::list<DSV> &list)
97       : inits_{inits}, exprAnalyzer_{a}, values_{a.context(), list} {}
98   const DataInitializations &inits() const { return inits_; }
99   bool HasSurplusValues() const { return !values_.IsAtEnd(); }
100   bool Scan(const parser::DataStmtObject &);
101   // Initializes all elements of whole variable or component
102   bool Scan(const Symbol &);
103 
104 private:
105   bool Scan(const parser::Variable &);
106   bool Scan(const parser::Designator &);
107   bool Scan(const parser::DataImpliedDo &);
108   bool Scan(const parser::DataIDoObject &);
109 
110   // Initializes all elements of a designator, which can be an array or section.
111   bool InitDesignator(const SomeExpr &);
112   // Initializes a single scalar object.
113   bool InitElement(const evaluate::OffsetSymbol &, const SomeExpr &designator);
114   // If the returned flag is true, emit a warning about CHARACTER misusage.
115   std::optional<std::pair<SomeExpr, bool>> ConvertElement(
116       const SomeExpr &, const evaluate::DynamicType &);
117 
118   DataInitializations &inits_;
119   evaluate::ExpressionAnalyzer &exprAnalyzer_;
120   ValueListIterator<DSV> values_;
121 };
122 
123 template <typename DSV>
124 bool DataInitializationCompiler<DSV>::Scan(
125     const parser::DataStmtObject &object) {
126   return common::visit(
127       common::visitors{
128           [&](const common::Indirection<parser::Variable> &var) {
129             return Scan(var.value());
130           },
131           [&](const parser::DataImpliedDo &ido) { return Scan(ido); },
132       },
133       object.u);
134 }
135 
136 template <typename DSV>
137 bool DataInitializationCompiler<DSV>::Scan(const parser::Variable &var) {
138   if (const auto *expr{GetExpr(exprAnalyzer_.context(), var)}) {
139     exprAnalyzer_.GetFoldingContext().messages().SetLocation(var.GetSource());
140     if (InitDesignator(*expr)) {
141       return true;
142     }
143   }
144   return false;
145 }
146 
147 template <typename DSV>
148 bool DataInitializationCompiler<DSV>::Scan(
149     const parser::Designator &designator) {
150   if (auto expr{exprAnalyzer_.Analyze(designator)}) {
151     exprAnalyzer_.GetFoldingContext().messages().SetLocation(
152         parser::FindSourceLocation(designator));
153     if (InitDesignator(*expr)) {
154       return true;
155     }
156   }
157   return false;
158 }
159 
160 template <typename DSV>
161 bool DataInitializationCompiler<DSV>::Scan(const parser::DataImpliedDo &ido) {
162   const auto &bounds{std::get<parser::DataImpliedDo::Bounds>(ido.t)};
163   auto name{bounds.name.thing.thing};
164   const auto *lowerExpr{
165       GetExpr(exprAnalyzer_.context(), bounds.lower.thing.thing)};
166   const auto *upperExpr{
167       GetExpr(exprAnalyzer_.context(), bounds.upper.thing.thing)};
168   const auto *stepExpr{bounds.step
169           ? GetExpr(exprAnalyzer_.context(), bounds.step->thing.thing)
170           : nullptr};
171   if (lowerExpr && upperExpr) {
172     // Fold the bounds expressions (again) in case any of them depend
173     // on outer implied DO loops.
174     evaluate::FoldingContext &context{exprAnalyzer_.GetFoldingContext()};
175     std::int64_t stepVal{1};
176     if (stepExpr) {
177       auto foldedStep{evaluate::Fold(context, SomeExpr{*stepExpr})};
178       stepVal = ToInt64(foldedStep).value_or(1);
179       if (stepVal == 0) {
180         exprAnalyzer_.Say(name.source,
181             "DATA statement implied DO loop has a step value of zero"_err_en_US);
182         return false;
183       }
184     }
185     auto foldedLower{evaluate::Fold(context, SomeExpr{*lowerExpr})};
186     auto lower{ToInt64(foldedLower)};
187     auto foldedUpper{evaluate::Fold(context, SomeExpr{*upperExpr})};
188     auto upper{ToInt64(foldedUpper)};
189     if (lower && upper) {
190       int kind{evaluate::ResultType<evaluate::ImpliedDoIndex>::kind};
191       if (const auto dynamicType{evaluate::DynamicType::From(*name.symbol)}) {
192         if (dynamicType->category() == TypeCategory::Integer) {
193           kind = dynamicType->kind();
194         }
195       }
196       if (exprAnalyzer_.AddImpliedDo(name.source, kind)) {
197         auto &value{context.StartImpliedDo(name.source, *lower)};
198         bool result{true};
199         for (auto n{(*upper - value + stepVal) / stepVal}; n > 0;
200              --n, value += stepVal) {
201           for (const auto &object :
202               std::get<std::list<parser::DataIDoObject>>(ido.t)) {
203             if (!Scan(object)) {
204               result = false;
205               break;
206             }
207           }
208         }
209         context.EndImpliedDo(name.source);
210         exprAnalyzer_.RemoveImpliedDo(name.source);
211         return result;
212       }
213     }
214   }
215   return false;
216 }
217 
218 template <typename DSV>
219 bool DataInitializationCompiler<DSV>::Scan(
220     const parser::DataIDoObject &object) {
221   return common::visit(
222       common::visitors{
223           [&](const parser::Scalar<common::Indirection<parser::Designator>>
224                   &var) { return Scan(var.thing.value()); },
225           [&](const common::Indirection<parser::DataImpliedDo> &ido) {
226             return Scan(ido.value());
227           },
228       },
229       object.u);
230 }
231 
232 template <typename DSV>
233 bool DataInitializationCompiler<DSV>::Scan(const Symbol &symbol) {
234   auto designator{exprAnalyzer_.Designate(evaluate::DataRef{symbol})};
235   CHECK(designator.has_value());
236   return InitDesignator(*designator);
237 }
238 
239 template <typename DSV>
240 bool DataInitializationCompiler<DSV>::InitDesignator(
241     const SomeExpr &designator) {
242   evaluate::FoldingContext &context{exprAnalyzer_.GetFoldingContext()};
243   evaluate::DesignatorFolder folder{context};
244   while (auto offsetSymbol{folder.FoldDesignator(designator)}) {
245     if (folder.isOutOfRange()) {
246       if (auto bad{evaluate::OffsetToDesignator(context, *offsetSymbol)}) {
247         exprAnalyzer_.context().Say(
248             "DATA statement designator '%s' is out of range"_err_en_US,
249             bad->AsFortran());
250       } else {
251         exprAnalyzer_.context().Say(
252             "DATA statement designator '%s' is out of range"_err_en_US,
253             designator.AsFortran());
254       }
255       return false;
256     } else if (!InitElement(*offsetSymbol, designator)) {
257       return false;
258     } else {
259       ++values_;
260     }
261   }
262   return folder.isEmpty();
263 }
264 
265 template <typename DSV>
266 std::optional<std::pair<SomeExpr, bool>>
267 DataInitializationCompiler<DSV>::ConvertElement(
268     const SomeExpr &expr, const evaluate::DynamicType &type) {
269   if (auto converted{evaluate::ConvertToType(type, SomeExpr{expr})}) {
270     return {std::make_pair(std::move(*converted), false)};
271   }
272   if (std::optional<std::string> chValue{
273           evaluate::GetScalarConstantValue<evaluate::Ascii>(expr)}) {
274     // Allow DATA initialization with Hollerith and kind=1 CHARACTER like
275     // (most) other Fortran compilers do.  Pad on the right with spaces
276     // when short, truncate the right if long.
277     // TODO: big-endian targets
278     auto bytes{static_cast<std::size_t>(evaluate::ToInt64(
279         type.MeasureSizeInBytes(exprAnalyzer_.GetFoldingContext(), false))
280                                             .value())};
281     evaluate::BOZLiteralConstant bits{0};
282     for (std::size_t j{0}; j < bytes; ++j) {
283       char ch{j >= chValue->size() ? ' ' : chValue->at(j)};
284       evaluate::BOZLiteralConstant chBOZ{static_cast<unsigned char>(ch)};
285       bits = bits.IOR(chBOZ.SHIFTL(8 * j));
286     }
287     if (auto converted{evaluate::ConvertToType(type, SomeExpr{bits})}) {
288       return {std::make_pair(std::move(*converted), true)};
289     }
290   }
291   SemanticsContext &context{exprAnalyzer_.context()};
292   if (context.IsEnabled(common::LanguageFeature::LogicalIntegerAssignment)) {
293     if (MaybeExpr converted{evaluate::DataConstantConversionExtension(
294             exprAnalyzer_.GetFoldingContext(), type, expr)}) {
295       if (context.ShouldWarn(
296               common::LanguageFeature::LogicalIntegerAssignment)) {
297         context.Say(
298             "nonstandard usage: initialization of %s with %s"_port_en_US,
299             type.AsFortran(), expr.GetType().value().AsFortran());
300       }
301       return {std::make_pair(std::move(*converted), false)};
302     }
303   }
304   return std::nullopt;
305 }
306 
307 template <typename DSV>
308 bool DataInitializationCompiler<DSV>::InitElement(
309     const evaluate::OffsetSymbol &offsetSymbol, const SomeExpr &designator) {
310   const Symbol &symbol{offsetSymbol.symbol()};
311   const Symbol *lastSymbol{GetLastSymbol(designator)};
312   bool isPointer{lastSymbol && IsPointer(*lastSymbol)};
313   bool isProcPointer{lastSymbol && IsProcedurePointer(*lastSymbol)};
314   evaluate::FoldingContext &context{exprAnalyzer_.GetFoldingContext()};
315   auto restorer{context.messages().SetLocation(values_.LocateSource())};
316 
317   const auto DescribeElement{[&]() {
318     if (auto badDesignator{
319             evaluate::OffsetToDesignator(context, offsetSymbol)}) {
320       return badDesignator->AsFortran();
321     } else {
322       // Error recovery
323       std::string buf;
324       llvm::raw_string_ostream ss{buf};
325       ss << offsetSymbol.symbol().name() << " offset " << offsetSymbol.offset()
326          << " bytes for " << offsetSymbol.size() << " bytes";
327       return ss.str();
328     }
329   }};
330   const auto GetImage{[&]() -> evaluate::InitialImage & {
331     auto iter{inits_.emplace(&symbol, symbol.size())};
332     auto &symbolInit{iter.first->second};
333     symbolInit.initializedRanges.emplace_back(
334         offsetSymbol.offset(), offsetSymbol.size());
335     return symbolInit.image;
336   }};
337   const auto OutOfRangeError{[&]() {
338     evaluate::AttachDeclaration(
339         exprAnalyzer_.context().Say(
340             "DATA statement designator '%s' is out of range for its variable '%s'"_err_en_US,
341             DescribeElement(), symbol.name()),
342         symbol);
343   }};
344 
345   if (values_.hasFatalError()) {
346     return false;
347   } else if (values_.IsAtEnd()) {
348     exprAnalyzer_.context().Say(
349         "DATA statement set has no value for '%s'"_err_en_US,
350         DescribeElement());
351     return false;
352   } else if (static_cast<std::size_t>(
353                  offsetSymbol.offset() + offsetSymbol.size()) > symbol.size()) {
354     OutOfRangeError();
355     return false;
356   }
357 
358   const SomeExpr *expr{*values_};
359   if (!expr) {
360     CHECK(exprAnalyzer_.context().AnyFatalError());
361   } else if (isPointer) {
362     if (static_cast<std::size_t>(offsetSymbol.offset() + offsetSymbol.size()) >
363         symbol.size()) {
364       OutOfRangeError();
365     } else if (evaluate::IsNullPointer(*expr)) {
366       // nothing to do; rely on zero initialization
367       return true;
368     } else if (isProcPointer) {
369       if (evaluate::IsProcedure(*expr)) {
370         if (CheckPointerAssignment(context, designator, *expr)) {
371           GetImage().AddPointer(offsetSymbol.offset(), *expr);
372           return true;
373         }
374       } else {
375         exprAnalyzer_.Say(
376             "Data object '%s' may not be used to initialize '%s', which is a procedure pointer"_err_en_US,
377             expr->AsFortran(), DescribeElement());
378       }
379     } else if (evaluate::IsProcedure(*expr)) {
380       exprAnalyzer_.Say(
381           "Procedure '%s' may not be used to initialize '%s', which is not a procedure pointer"_err_en_US,
382           expr->AsFortran(), DescribeElement());
383     } else if (CheckInitialTarget(context, designator, *expr)) {
384       GetImage().AddPointer(offsetSymbol.offset(), *expr);
385       return true;
386     }
387   } else if (evaluate::IsNullPointer(*expr)) {
388     exprAnalyzer_.Say("Initializer for '%s' must not be a pointer"_err_en_US,
389         DescribeElement());
390   } else if (evaluate::IsProcedure(*expr)) {
391     exprAnalyzer_.Say("Initializer for '%s' must not be a procedure"_err_en_US,
392         DescribeElement());
393   } else if (auto designatorType{designator.GetType()}) {
394     if (expr->Rank() > 0) {
395       // Because initial-data-target is ambiguous with scalar-constant and
396       // scalar-constant-subobject at parse time, enforcement of scalar-*
397       // must be deferred to here.
398       exprAnalyzer_.Say(
399           "DATA statement value initializes '%s' with an array"_err_en_US,
400           DescribeElement());
401     } else if (auto converted{ConvertElement(*expr, *designatorType)}) {
402       // value non-pointer initialization
403       if (IsBOZLiteral(*expr) &&
404           designatorType->category() != TypeCategory::Integer) { // 8.6.7(11)
405         exprAnalyzer_.Say(
406             "BOZ literal should appear in a DATA statement only as a value for an integer object, but '%s' is '%s'"_port_en_US,
407             DescribeElement(), designatorType->AsFortran());
408       } else if (converted->second) {
409         exprAnalyzer_.context().Say(
410             "DATA statement value initializes '%s' of type '%s' with CHARACTER"_port_en_US,
411             DescribeElement(), designatorType->AsFortran());
412       }
413       auto folded{evaluate::Fold(context, std::move(converted->first))};
414       switch (GetImage().Add(
415           offsetSymbol.offset(), offsetSymbol.size(), folded, context)) {
416       case evaluate::InitialImage::Ok:
417         return true;
418       case evaluate::InitialImage::NotAConstant:
419         exprAnalyzer_.Say(
420             "DATA statement value '%s' for '%s' is not a constant"_err_en_US,
421             folded.AsFortran(), DescribeElement());
422         break;
423       case evaluate::InitialImage::OutOfRange:
424         OutOfRangeError();
425         break;
426       default:
427         CHECK(exprAnalyzer_.context().AnyFatalError());
428         break;
429       }
430     } else {
431       exprAnalyzer_.context().Say(
432           "DATA statement value could not be converted to the type '%s' of the object '%s'"_err_en_US,
433           designatorType->AsFortran(), DescribeElement());
434     }
435   } else {
436     CHECK(exprAnalyzer_.context().AnyFatalError());
437   }
438   return false;
439 }
440 
441 void AccumulateDataInitializations(DataInitializations &inits,
442     evaluate::ExpressionAnalyzer &exprAnalyzer,
443     const parser::DataStmtSet &set) {
444   DataInitializationCompiler scanner{
445       inits, exprAnalyzer, std::get<std::list<parser::DataStmtValue>>(set.t)};
446   for (const auto &object :
447       std::get<std::list<parser::DataStmtObject>>(set.t)) {
448     if (!scanner.Scan(object)) {
449       return;
450     }
451   }
452   if (scanner.HasSurplusValues()) {
453     exprAnalyzer.context().Say(
454         "DATA statement set has more values than objects"_err_en_US);
455   }
456 }
457 
458 void AccumulateDataInitializations(DataInitializations &inits,
459     evaluate::ExpressionAnalyzer &exprAnalyzer, const Symbol &symbol,
460     const std::list<common::Indirection<parser::DataStmtValue>> &list) {
461   DataInitializationCompiler<common::Indirection<parser::DataStmtValue>>
462       scanner{inits, exprAnalyzer, list};
463   if (scanner.Scan(symbol) && scanner.HasSurplusValues()) {
464     exprAnalyzer.context().Say(
465         "DATA statement set has more values than objects"_err_en_US);
466   }
467 }
468 
469 // Looks for default derived type component initialization -- but
470 // *not* allocatables.
471 static const DerivedTypeSpec *HasDefaultInitialization(const Symbol &symbol) {
472   if (const auto *object{symbol.detailsIf<ObjectEntityDetails>()}) {
473     if (object->init().has_value()) {
474       return nullptr; // init is explicit, not default
475     } else if (!object->isDummy() && object->type()) {
476       if (const DerivedTypeSpec * derived{object->type()->AsDerived()}) {
477         DirectComponentIterator directs{*derived};
478         if (std::find_if(
479                 directs.begin(), directs.end(), [](const Symbol &component) {
480                   return !IsAllocatable(component) &&
481                       HasDeclarationInitializer(component);
482                 })) {
483           return derived;
484         }
485       }
486     }
487   }
488   return nullptr;
489 }
490 
491 // PopulateWithComponentDefaults() adds initializations to an instance
492 // of SymbolDataInitialization containing all of the default component
493 // initializers
494 
495 static void PopulateWithComponentDefaults(SymbolDataInitialization &init,
496     std::size_t offset, const DerivedTypeSpec &derived,
497     evaluate::FoldingContext &foldingContext);
498 
499 static void PopulateWithComponentDefaults(SymbolDataInitialization &init,
500     std::size_t offset, const DerivedTypeSpec &derived,
501     evaluate::FoldingContext &foldingContext, const Symbol &symbol) {
502   if (auto extents{evaluate::GetConstantExtents(foldingContext, symbol)}) {
503     const Scope &scope{derived.scope() ? *derived.scope()
504                                        : DEREF(derived.typeSymbol().scope())};
505     std::size_t stride{scope.size()};
506     if (std::size_t alignment{scope.alignment().value_or(0)}) {
507       stride = ((stride + alignment - 1) / alignment) * alignment;
508     }
509     for (auto elements{evaluate::GetSize(*extents)}; elements-- > 0;
510          offset += stride) {
511       PopulateWithComponentDefaults(init, offset, derived, foldingContext);
512     }
513   }
514 }
515 
516 // F'2018 19.5.3(10) allows storage-associated default component initialization
517 // when the values are identical.
518 static void PopulateWithComponentDefaults(SymbolDataInitialization &init,
519     std::size_t offset, const DerivedTypeSpec &derived,
520     evaluate::FoldingContext &foldingContext) {
521   const Scope &scope{
522       derived.scope() ? *derived.scope() : DEREF(derived.typeSymbol().scope())};
523   for (const auto &pair : scope) {
524     const Symbol &component{*pair.second};
525     std::size_t componentOffset{offset + component.offset()};
526     if (const auto *object{component.detailsIf<ObjectEntityDetails>()}) {
527       if (!IsAllocatable(component) && !IsAutomatic(component)) {
528         bool initialized{false};
529         if (object->init()) {
530           initialized = true;
531           if (IsPointer(component)) {
532             if (auto extant{init.image.AsConstantPointer(componentOffset)}) {
533               initialized = !(*extant == *object->init());
534             }
535             if (initialized) {
536               init.image.AddPointer(componentOffset, *object->init());
537             }
538           } else { // data, not pointer
539             if (auto dyType{evaluate::DynamicType::From(component)}) {
540               if (auto extents{evaluate::GetConstantExtents(
541                       foldingContext, component)}) {
542                 if (auto extant{init.image.AsConstant(
543                         foldingContext, *dyType, *extents, componentOffset)}) {
544                   initialized = !(*extant == *object->init());
545                 }
546               }
547             }
548             if (initialized) {
549               init.image.Add(componentOffset, component.size(), *object->init(),
550                   foldingContext);
551             }
552           }
553         } else if (const DeclTypeSpec * type{component.GetType()}) {
554           if (const DerivedTypeSpec * componentDerived{type->AsDerived()}) {
555             PopulateWithComponentDefaults(init, componentOffset,
556                 *componentDerived, foldingContext, component);
557           }
558         }
559         if (initialized) {
560           init.initializedRanges.emplace_back(
561               componentOffset, component.size());
562         }
563       }
564     } else if (const auto *proc{component.detailsIf<ProcEntityDetails>()}) {
565       if (proc->init() && *proc->init()) {
566         SomeExpr procPtrInit{evaluate::ProcedureDesignator{**proc->init()}};
567         auto extant{init.image.AsConstantPointer(componentOffset)};
568         if (!extant || !(*extant == procPtrInit)) {
569           init.initializedRanges.emplace_back(
570               componentOffset, component.size());
571           init.image.AddPointer(componentOffset, std::move(procPtrInit));
572         }
573       }
574     }
575   }
576 }
577 
578 static bool CheckForOverlappingInitialization(
579     const std::list<SymbolRef> &symbols,
580     SymbolDataInitialization &initialization,
581     evaluate::ExpressionAnalyzer &exprAnalyzer, const std::string &what) {
582   bool result{true};
583   auto &context{exprAnalyzer.GetFoldingContext()};
584   initialization.initializedRanges.sort();
585   ConstantSubscript next{0};
586   for (const auto &range : initialization.initializedRanges) {
587     if (range.start() < next) {
588       result = false; // error: overlap
589       bool hit{false};
590       for (const Symbol &symbol : symbols) {
591         auto offset{range.start() -
592             static_cast<ConstantSubscript>(
593                 symbol.offset() - symbols.front()->offset())};
594         if (offset >= 0) {
595           if (auto badDesignator{evaluate::OffsetToDesignator(
596                   context, symbol, offset, range.size())}) {
597             hit = true;
598             exprAnalyzer.Say(symbol.name(),
599                 "%s affect '%s' more than once"_err_en_US, what,
600                 badDesignator->AsFortran());
601           }
602         }
603       }
604       CHECK(hit);
605     }
606     next = range.start() + range.size();
607     CHECK(next <= static_cast<ConstantSubscript>(initialization.image.size()));
608   }
609   return result;
610 }
611 
612 static void IncorporateExplicitInitialization(
613     SymbolDataInitialization &combined, DataInitializations &inits,
614     const Symbol &symbol, ConstantSubscript firstOffset,
615     evaluate::FoldingContext &foldingContext) {
616   auto iter{inits.find(&symbol)};
617   const auto offset{symbol.offset() - firstOffset};
618   if (iter != inits.end()) { // DATA statement initialization
619     for (const auto &range : iter->second.initializedRanges) {
620       auto at{offset + range.start()};
621       combined.initializedRanges.emplace_back(at, range.size());
622       combined.image.Incorporate(
623           at, iter->second.image, range.start(), range.size());
624     }
625     if (removeOriginalInits) {
626       inits.erase(iter);
627     }
628   } else { // Declaration initialization
629     Symbol &mutableSymbol{const_cast<Symbol &>(symbol)};
630     if (IsPointer(mutableSymbol)) {
631       if (auto *object{mutableSymbol.detailsIf<ObjectEntityDetails>()}) {
632         if (object->init()) {
633           combined.initializedRanges.emplace_back(offset, mutableSymbol.size());
634           combined.image.AddPointer(offset, *object->init());
635           if (removeOriginalInits) {
636             object->init().reset();
637           }
638         }
639       } else if (auto *proc{mutableSymbol.detailsIf<ProcEntityDetails>()}) {
640         if (proc->init() && *proc->init()) {
641           combined.initializedRanges.emplace_back(offset, mutableSymbol.size());
642           combined.image.AddPointer(
643               offset, SomeExpr{evaluate::ProcedureDesignator{**proc->init()}});
644           if (removeOriginalInits) {
645             proc->init().reset();
646           }
647         }
648       }
649     } else if (auto *object{mutableSymbol.detailsIf<ObjectEntityDetails>()}) {
650       if (!IsNamedConstant(mutableSymbol) && object->init()) {
651         combined.initializedRanges.emplace_back(offset, mutableSymbol.size());
652         combined.image.Add(
653             offset, mutableSymbol.size(), *object->init(), foldingContext);
654         if (removeOriginalInits) {
655           object->init().reset();
656         }
657       }
658     }
659   }
660 }
661 
662 // Finds the size of the smallest element type in a list of
663 // storage-associated objects.
664 static std::size_t ComputeMinElementBytes(
665     const std::list<SymbolRef> &associated,
666     evaluate::FoldingContext &foldingContext) {
667   std::size_t minElementBytes{1};
668   const Symbol &first{*associated.front()};
669   for (const Symbol &s : associated) {
670     if (auto dyType{evaluate::DynamicType::From(s)}) {
671       auto size{static_cast<std::size_t>(
672           evaluate::ToInt64(dyType->MeasureSizeInBytes(foldingContext, true))
673               .value_or(1))};
674       if (std::size_t alignment{dyType->GetAlignment(foldingContext)}) {
675         size = ((size + alignment - 1) / alignment) * alignment;
676       }
677       if (&s == &first) {
678         minElementBytes = size;
679       } else {
680         minElementBytes = std::min(minElementBytes, size);
681       }
682     } else {
683       minElementBytes = 1;
684     }
685   }
686   return minElementBytes;
687 }
688 
689 // Checks for overlapping initialization errors in a list of
690 // storage-associated objects.  Default component initializations
691 // are allowed to be overridden by explicit initializations.
692 // If the objects are static, save the combined initializer as
693 // a compiler-created object that covers all of them.
694 static bool CombineEquivalencedInitialization(
695     const std::list<SymbolRef> &associated,
696     evaluate::ExpressionAnalyzer &exprAnalyzer, DataInitializations &inits) {
697   // Compute the minimum common granularity and total size
698   const Symbol &first{*associated.front()};
699   std::size_t maxLimit{0};
700   for (const Symbol &s : associated) {
701     CHECK(s.offset() >= first.offset());
702     auto limit{s.offset() + s.size()};
703     if (limit > maxLimit) {
704       maxLimit = limit;
705     }
706   }
707   auto bytes{static_cast<common::ConstantSubscript>(maxLimit - first.offset())};
708   Scope &scope{const_cast<Scope &>(first.owner())};
709   // Combine the initializations of the associated objects.
710   // Apply all default initializations first.
711   SymbolDataInitialization combined{static_cast<std::size_t>(bytes)};
712   auto &foldingContext{exprAnalyzer.GetFoldingContext()};
713   for (const Symbol &s : associated) {
714     if (!IsNamedConstant(s)) {
715       if (const auto *derived{HasDefaultInitialization(s)}) {
716         PopulateWithComponentDefaults(
717             combined, s.offset() - first.offset(), *derived, foldingContext, s);
718       }
719     }
720   }
721   if (!CheckForOverlappingInitialization(associated, combined, exprAnalyzer,
722           "Distinct default component initializations of equivalenced objects"s)) {
723     return false;
724   }
725   // Don't complain about overlap between explicit initializations and
726   // default initializations.
727   combined.initializedRanges.clear();
728   // Now overlay all explicit initializations from DATA statements and
729   // from initializers in declarations.
730   for (const Symbol &symbol : associated) {
731     IncorporateExplicitInitialization(
732         combined, inits, symbol, first.offset(), foldingContext);
733   }
734   if (!CheckForOverlappingInitialization(associated, combined, exprAnalyzer,
735           "Explicit initializations of equivalenced objects"s)) {
736     return false;
737   }
738   // If the items are in static storage, save the final initialization.
739   if (std::find_if(associated.begin(), associated.end(),
740           [](SymbolRef ref) { return IsSaved(*ref); }) != associated.end()) {
741     // Create a compiler array temp that overlaps all the items.
742     SourceName name{exprAnalyzer.context().GetTempName(scope)};
743     auto emplaced{
744         scope.try_emplace(name, Attrs{Attr::SAVE}, ObjectEntityDetails{})};
745     CHECK(emplaced.second);
746     Symbol &combinedSymbol{*emplaced.first->second};
747     combinedSymbol.set(Symbol::Flag::CompilerCreated);
748     inits.emplace(&combinedSymbol, std::move(combined));
749     auto &details{combinedSymbol.get<ObjectEntityDetails>()};
750     combinedSymbol.set_offset(first.offset());
751     combinedSymbol.set_size(bytes);
752     std::size_t minElementBytes{
753         ComputeMinElementBytes(associated, foldingContext)};
754     if (!evaluate::IsValidKindOfIntrinsicType(
755             TypeCategory::Integer, minElementBytes) ||
756         (bytes % minElementBytes) != 0) {
757       minElementBytes = 1;
758     }
759     const DeclTypeSpec &typeSpec{scope.MakeNumericType(
760         TypeCategory::Integer, KindExpr{minElementBytes})};
761     details.set_type(typeSpec);
762     ArraySpec arraySpec;
763     arraySpec.emplace_back(ShapeSpec::MakeExplicit(Bound{
764         bytes / static_cast<common::ConstantSubscript>(minElementBytes)}));
765     details.set_shape(arraySpec);
766     if (const auto *commonBlock{FindCommonBlockContaining(first)}) {
767       details.set_commonBlock(*commonBlock);
768     }
769     // Add an EQUIVALENCE set to the scope so that the new object appears in
770     // the results of GetStorageAssociations().
771     auto &newSet{scope.equivalenceSets().emplace_back()};
772     newSet.emplace_back(combinedSymbol);
773     newSet.emplace_back(const_cast<Symbol &>(first));
774   }
775   return true;
776 }
777 
778 // When a statically-allocated derived type variable has no explicit
779 // initialization, but its type has at least one nonallocatable ultimate
780 // component with default initialization, make its initialization explicit.
781 [[maybe_unused]] static void MakeDefaultInitializationExplicit(
782     const Scope &scope, const std::list<std::list<SymbolRef>> &associations,
783     evaluate::FoldingContext &foldingContext, DataInitializations &inits) {
784   UnorderedSymbolSet equivalenced;
785   for (const std::list<SymbolRef> &association : associations) {
786     for (const Symbol &symbol : association) {
787       equivalenced.emplace(symbol);
788     }
789   }
790   for (const auto &pair : scope) {
791     const Symbol &symbol{*pair.second};
792     if (!symbol.test(Symbol::Flag::InDataStmt) &&
793         !HasDeclarationInitializer(symbol) && IsSaved(symbol) &&
794         equivalenced.find(symbol) == equivalenced.end()) {
795       // Static object, no local storage association, no explicit initialization
796       if (const DerivedTypeSpec * derived{HasDefaultInitialization(symbol)}) {
797         auto newInitIter{inits.emplace(&symbol, symbol.size())};
798         CHECK(newInitIter.second);
799         auto &newInit{newInitIter.first->second};
800         PopulateWithComponentDefaults(
801             newInit, 0, *derived, foldingContext, symbol);
802       }
803     }
804   }
805 }
806 
807 // Traverses the Scopes to:
808 // 1) combine initialization of equivalenced objects, &
809 // 2) optionally make initialization explicit for otherwise uninitialized static
810 //    objects of derived types with default component initialization
811 // Returns false on error.
812 static bool ProcessScopes(const Scope &scope,
813     evaluate::ExpressionAnalyzer &exprAnalyzer, DataInitializations &inits) {
814   bool result{true}; // no error
815   switch (scope.kind()) {
816   case Scope::Kind::Global:
817   case Scope::Kind::Module:
818   case Scope::Kind::MainProgram:
819   case Scope::Kind::Subprogram:
820   case Scope::Kind::BlockData:
821   case Scope::Kind::Block: {
822     std::list<std::list<SymbolRef>> associations{GetStorageAssociations(scope)};
823     for (const std::list<SymbolRef> &associated : associations) {
824       if (std::find_if(associated.begin(), associated.end(), [](SymbolRef ref) {
825             return IsInitialized(*ref);
826           }) != associated.end()) {
827         result &=
828             CombineEquivalencedInitialization(associated, exprAnalyzer, inits);
829       }
830     }
831     if constexpr (makeDefaultInitializationExplicit) {
832       MakeDefaultInitializationExplicit(
833           scope, associations, exprAnalyzer.GetFoldingContext(), inits);
834     }
835     for (const Scope &child : scope.children()) {
836       result &= ProcessScopes(child, exprAnalyzer, inits);
837     }
838   } break;
839   default:;
840   }
841   return result;
842 }
843 
844 // Converts the static initialization image for a single symbol with
845 // one or more DATA statement appearances.
846 void ConstructInitializer(const Symbol &symbol,
847     SymbolDataInitialization &initialization,
848     evaluate::ExpressionAnalyzer &exprAnalyzer) {
849   std::list<SymbolRef> symbols{symbol};
850   CheckForOverlappingInitialization(
851       symbols, initialization, exprAnalyzer, "DATA statement initializations"s);
852   auto &context{exprAnalyzer.GetFoldingContext()};
853   if (const auto *proc{symbol.detailsIf<ProcEntityDetails>()}) {
854     CHECK(IsProcedurePointer(symbol));
855     auto &mutableProc{const_cast<ProcEntityDetails &>(*proc)};
856     if (MaybeExpr expr{initialization.image.AsConstantPointer()}) {
857       if (const auto *procDesignator{
858               std::get_if<evaluate::ProcedureDesignator>(&expr->u)}) {
859         CHECK(!procDesignator->GetComponent());
860         mutableProc.set_init(DEREF(procDesignator->GetSymbol()));
861       } else {
862         CHECK(evaluate::IsNullPointer(*expr));
863         mutableProc.set_init(nullptr);
864       }
865     } else {
866       mutableProc.set_init(nullptr);
867     }
868   } else if (const auto *object{symbol.detailsIf<ObjectEntityDetails>()}) {
869     auto &mutableObject{const_cast<ObjectEntityDetails &>(*object)};
870     if (IsPointer(symbol)) {
871       if (auto ptr{initialization.image.AsConstantPointer()}) {
872         mutableObject.set_init(*ptr);
873       } else {
874         mutableObject.set_init(SomeExpr{evaluate::NullPointer{}});
875       }
876     } else if (auto symbolType{evaluate::DynamicType::From(symbol)}) {
877       if (auto extents{evaluate::GetConstantExtents(context, symbol)}) {
878         mutableObject.set_init(
879             initialization.image.AsConstant(context, *symbolType, *extents));
880       } else {
881         exprAnalyzer.Say(symbol.name(),
882             "internal: unknown shape for '%s' while constructing initializer from DATA"_err_en_US,
883             symbol.name());
884         return;
885       }
886     } else {
887       exprAnalyzer.Say(symbol.name(),
888           "internal: no type for '%s' while constructing initializer from DATA"_err_en_US,
889           symbol.name());
890       return;
891     }
892     if (!object->init()) {
893       exprAnalyzer.Say(symbol.name(),
894           "internal: could not construct an initializer from DATA statements for '%s'"_err_en_US,
895           symbol.name());
896     }
897   } else {
898     CHECK(exprAnalyzer.context().AnyFatalError());
899   }
900 }
901 
902 void ConvertToInitializers(
903     DataInitializations &inits, evaluate::ExpressionAnalyzer &exprAnalyzer) {
904   if (ProcessScopes(
905           exprAnalyzer.context().globalScope(), exprAnalyzer, inits)) {
906     for (auto &[symbolPtr, initialization] : inits) {
907       ConstructInitializer(*symbolPtr, initialization, exprAnalyzer);
908     }
909   }
910 }
911 } // namespace Fortran::semantics
912