1 //===-- lib/Evaluate/variable.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 #include "flang/Evaluate/variable.h"
10 #include "flang/Common/idioms.h"
11 #include "flang/Evaluate/fold.h"
12 #include "flang/Evaluate/tools.h"
13 #include "flang/Parser/char-block.h"
14 #include "flang/Parser/characters.h"
15 #include "flang/Parser/message.h"
16 #include "flang/Semantics/symbol.h"
17 #include <type_traits>
18 
19 using namespace Fortran::parser::literals;
20 
21 namespace Fortran::evaluate {
22 
23 // Constructors, accessors, mutators
24 
25 Triplet::Triplet() : stride_{Expr<SubscriptInteger>{1}} {}
26 
27 Triplet::Triplet(std::optional<Expr<SubscriptInteger>> &&l,
28     std::optional<Expr<SubscriptInteger>> &&u,
29     std::optional<Expr<SubscriptInteger>> &&s)
30     : stride_{s ? std::move(*s) : Expr<SubscriptInteger>{1}} {
31   if (l) {
32     lower_.emplace(std::move(*l));
33   }
34   if (u) {
35     upper_.emplace(std::move(*u));
36   }
37 }
38 
39 std::optional<Expr<SubscriptInteger>> Triplet::lower() const {
40   if (lower_) {
41     return {lower_.value().value()};
42   }
43   return std::nullopt;
44 }
45 
46 Triplet &Triplet::set_lower(Expr<SubscriptInteger> &&expr) {
47   lower_.emplace(std::move(expr));
48   return *this;
49 }
50 
51 std::optional<Expr<SubscriptInteger>> Triplet::upper() const {
52   if (upper_) {
53     return {upper_.value().value()};
54   }
55   return std::nullopt;
56 }
57 
58 Triplet &Triplet::set_upper(Expr<SubscriptInteger> &&expr) {
59   upper_.emplace(std::move(expr));
60   return *this;
61 }
62 
63 Expr<SubscriptInteger> Triplet::stride() const { return stride_.value(); }
64 
65 Triplet &Triplet::set_stride(Expr<SubscriptInteger> &&expr) {
66   stride_.value() = std::move(expr);
67   return *this;
68 }
69 
70 bool Triplet::IsStrideOne() const {
71   if (auto stride{ToInt64(stride_.value())}) {
72     return stride == 1;
73   } else {
74     return false;
75   }
76 }
77 
78 CoarrayRef::CoarrayRef(SymbolVector &&base, std::vector<Subscript> &&ss,
79     std::vector<Expr<SubscriptInteger>> &&css)
80     : base_{std::move(base)}, subscript_(std::move(ss)),
81       cosubscript_(std::move(css)) {
82   CHECK(!base_.empty());
83   CHECK(!cosubscript_.empty());
84 }
85 
86 std::optional<Expr<SomeInteger>> CoarrayRef::stat() const {
87   if (stat_) {
88     return stat_.value().value();
89   } else {
90     return std::nullopt;
91   }
92 }
93 
94 std::optional<Expr<SomeInteger>> CoarrayRef::team() const {
95   if (team_) {
96     return team_.value().value();
97   } else {
98     return std::nullopt;
99   }
100 }
101 
102 CoarrayRef &CoarrayRef::set_stat(Expr<SomeInteger> &&v) {
103   CHECK(IsVariable(v));
104   stat_.emplace(std::move(v));
105   return *this;
106 }
107 
108 CoarrayRef &CoarrayRef::set_team(Expr<SomeInteger> &&v, bool isTeamNumber) {
109   CHECK(IsVariable(v));
110   team_.emplace(std::move(v));
111   teamIsTeamNumber_ = isTeamNumber;
112   return *this;
113 }
114 
115 const Symbol &CoarrayRef::GetFirstSymbol() const { return base_.front(); }
116 
117 const Symbol &CoarrayRef::GetLastSymbol() const { return base_.back(); }
118 
119 void Substring::SetBounds(std::optional<Expr<SubscriptInteger>> &lower,
120     std::optional<Expr<SubscriptInteger>> &upper) {
121   if (lower) {
122     set_lower(std::move(lower.value()));
123   }
124   if (upper) {
125     set_upper(std::move(upper.value()));
126   }
127 }
128 
129 Expr<SubscriptInteger> Substring::lower() const {
130   if (lower_) {
131     return lower_.value().value();
132   } else {
133     return AsExpr(Constant<SubscriptInteger>{1});
134   }
135 }
136 
137 Substring &Substring::set_lower(Expr<SubscriptInteger> &&expr) {
138   lower_.emplace(std::move(expr));
139   return *this;
140 }
141 
142 std::optional<Expr<SubscriptInteger>> Substring::upper() const {
143   if (upper_) {
144     return upper_.value().value();
145   } else {
146     return std::visit(
147         common::visitors{
148             [](const DataRef &dataRef) { return dataRef.LEN(); },
149             [](const StaticDataObject::Pointer &object)
150                 -> std::optional<Expr<SubscriptInteger>> {
151               return AsExpr(Constant<SubscriptInteger>{object->data().size()});
152             },
153         },
154         parent_);
155   }
156 }
157 
158 Substring &Substring::set_upper(Expr<SubscriptInteger> &&expr) {
159   upper_.emplace(std::move(expr));
160   return *this;
161 }
162 
163 std::optional<Expr<SomeCharacter>> Substring::Fold(FoldingContext &context) {
164   if (!lower_) {
165     lower_ = AsExpr(Constant<SubscriptInteger>{1});
166   }
167   lower_.value() = evaluate::Fold(context, std::move(lower_.value().value()));
168   std::optional<ConstantSubscript> lbi{ToInt64(lower_.value().value())};
169   if (lbi && *lbi < 1) {
170     context.messages().Say(
171         "Lower bound (%jd) on substring is less than one"_en_US, *lbi);
172     *lbi = 1;
173     lower_ = AsExpr(Constant<SubscriptInteger>{1});
174   }
175   if (!upper_) {
176     upper_ = upper();
177     if (!upper_) {
178       return std::nullopt;
179     }
180   }
181   upper_.value() = evaluate::Fold(context, std::move(upper_.value().value()));
182   if (std::optional<ConstantSubscript> ubi{ToInt64(upper_.value().value())}) {
183     auto *literal{std::get_if<StaticDataObject::Pointer>(&parent_)};
184     std::optional<ConstantSubscript> length;
185     if (literal) {
186       length = (*literal)->data().size();
187     } else if (const Symbol * symbol{GetLastSymbol()}) {
188       if (const semantics::DeclTypeSpec * type{symbol->GetType()}) {
189         if (type->category() == semantics::DeclTypeSpec::Character) {
190           length = ToInt64(type->characterTypeSpec().length().GetExplicit());
191         }
192       }
193     }
194     if (*ubi < 1 || (lbi && *ubi < *lbi)) {
195       // Zero-length string: canonicalize
196       *lbi = 1, *ubi = 0;
197       lower_ = AsExpr(Constant<SubscriptInteger>{*lbi});
198       upper_ = AsExpr(Constant<SubscriptInteger>{*ubi});
199     } else if (length && *ubi > *length) {
200       context.messages().Say("Upper bound (%jd) on substring is greater "
201                              "than character length (%jd)"_en_US,
202           *ubi, *length);
203       *ubi = *length;
204     }
205     if (lbi && literal) {
206       CHECK(*ubi >= *lbi);
207       auto newStaticData{StaticDataObject::Create()};
208       auto items{*ubi - *lbi + 1};
209       auto width{(*literal)->itemBytes()};
210       auto bytes{items * width};
211       auto startByte{(*lbi - 1) * width};
212       const auto *from{&(*literal)->data()[0] + startByte};
213       for (auto j{0}; j < bytes; ++j) {
214         newStaticData->data().push_back(from[j]);
215       }
216       parent_ = newStaticData;
217       lower_ = AsExpr(Constant<SubscriptInteger>{1});
218       ConstantSubscript length = newStaticData->data().size();
219       upper_ = AsExpr(Constant<SubscriptInteger>{length});
220       switch (width) {
221       case 1:
222         return {
223             AsCategoryExpr(AsExpr(Constant<Type<TypeCategory::Character, 1>>{
224                 *newStaticData->AsString()}))};
225       case 2:
226         return {AsCategoryExpr(Constant<Type<TypeCategory::Character, 2>>{
227             *newStaticData->AsU16String()})};
228       case 4:
229         return {AsCategoryExpr(Constant<Type<TypeCategory::Character, 4>>{
230             *newStaticData->AsU32String()})};
231       default:
232         CRASH_NO_CASE;
233       }
234     }
235   }
236   return std::nullopt;
237 }
238 
239 DescriptorInquiry::DescriptorInquiry(
240     const NamedEntity &base, Field field, int dim)
241     : base_{base}, field_{field}, dimension_{dim} {
242   const Symbol &last{base_.GetLastSymbol()};
243   CHECK(IsDescriptor(last));
244   CHECK((field == Field::Len && dim == 0) ||
245       (field != Field::Len && dim >= 0 && dim < last.Rank()));
246 }
247 
248 DescriptorInquiry::DescriptorInquiry(NamedEntity &&base, Field field, int dim)
249     : base_{std::move(base)}, field_{field}, dimension_{dim} {
250   const Symbol &last{base_.GetLastSymbol()};
251   CHECK(IsDescriptor(last));
252   CHECK((field == Field::Len && dim == 0) ||
253       (field != Field::Len && dim >= 0 && dim < last.Rank()));
254 }
255 
256 // LEN()
257 static std::optional<Expr<SubscriptInteger>> SymbolLEN(const Symbol &sym) {
258   if (auto dyType{DynamicType::From(sym)}) {
259     if (const semantics::ParamValue * len{dyType->charLength()}) {
260       if (len->isExplicit()) {
261         if (auto intExpr{len->GetExplicit()}) {
262           return ConvertToType<SubscriptInteger>(*std::move(intExpr));
263         } else {
264           // There was an error constructing this symbol's type.  It should
265           // have a length expression, but we couldn't retrieve it
266           return std::nullopt;
267         }
268       } else {
269         return Expr<SubscriptInteger>{
270             DescriptorInquiry{NamedEntity{sym}, DescriptorInquiry::Field::Len}};
271       }
272     }
273   }
274   return std::nullopt;
275 }
276 
277 std::optional<Expr<SubscriptInteger>> BaseObject::LEN() const {
278   return std::visit(
279       common::visitors{
280           [](const Symbol &symbol) { return SymbolLEN(symbol); },
281           [](const StaticDataObject::Pointer &object)
282               -> std::optional<Expr<SubscriptInteger>> {
283             return AsExpr(Constant<SubscriptInteger>{object->data().size()});
284           },
285       },
286       u);
287 }
288 
289 std::optional<Expr<SubscriptInteger>> Component::LEN() const {
290   return SymbolLEN(GetLastSymbol());
291 }
292 
293 std::optional<Expr<SubscriptInteger>> NamedEntity::LEN() const {
294   return SymbolLEN(GetLastSymbol());
295 }
296 
297 std::optional<Expr<SubscriptInteger>> ArrayRef::LEN() const {
298   return base_.LEN();
299 }
300 
301 std::optional<Expr<SubscriptInteger>> CoarrayRef::LEN() const {
302   return SymbolLEN(GetLastSymbol());
303 }
304 
305 std::optional<Expr<SubscriptInteger>> DataRef::LEN() const {
306   return std::visit(common::visitors{
307                         [](SymbolRef symbol) { return SymbolLEN(symbol); },
308                         [](const auto &x) { return x.LEN(); },
309                     },
310       u);
311 }
312 
313 std::optional<Expr<SubscriptInteger>> Substring::LEN() const {
314   if (auto top{upper()}) {
315     return AsExpr(Extremum<SubscriptInteger>{Ordering::Greater,
316         AsExpr(Constant<SubscriptInteger>{0}),
317         *std::move(top) - lower() + AsExpr(Constant<SubscriptInteger>{1})});
318   } else {
319     return std::nullopt;
320   }
321 }
322 
323 template <typename T>
324 std::optional<Expr<SubscriptInteger>> Designator<T>::LEN() const {
325   if constexpr (T::category == TypeCategory::Character) {
326     return std::visit(common::visitors{
327                           [](SymbolRef symbol) { return SymbolLEN(symbol); },
328                           [](const auto &x) { return x.LEN(); },
329                       },
330         u);
331   } else {
332     common::die("Designator<non-char>::LEN() called");
333     return std::nullopt;
334   }
335 }
336 
337 std::optional<Expr<SubscriptInteger>> ProcedureDesignator::LEN() const {
338   using T = std::optional<Expr<SubscriptInteger>>;
339   return std::visit(
340       common::visitors{
341           [](SymbolRef symbol) -> T { return SymbolLEN(symbol); },
342           [](const common::CopyableIndirection<Component> &c) -> T {
343             return c.value().LEN();
344           },
345           [](const SpecificIntrinsic &i) -> T {
346             if (i.name == "char") {
347               return Expr<SubscriptInteger>{1};
348             }
349             // Some other cases whose results' lengths can be determined
350             // from the lengths of their arguments are handled in
351             // ProcedureRef::LEN().
352             return std::nullopt;
353           },
354       },
355       u);
356 }
357 
358 // Rank()
359 int BaseObject::Rank() const {
360   return std::visit(common::visitors{
361                         [](SymbolRef symbol) { return symbol->Rank(); },
362                         [](const StaticDataObject::Pointer &) { return 0; },
363                     },
364       u);
365 }
366 
367 int Component::Rank() const {
368   if (int rank{symbol_->Rank()}; rank > 0) {
369     return rank;
370   }
371   return base().Rank();
372 }
373 
374 int NamedEntity::Rank() const {
375   return std::visit(common::visitors{
376                         [](const SymbolRef s) { return s->Rank(); },
377                         [](const Component &c) { return c.Rank(); },
378                     },
379       u_);
380 }
381 
382 int Subscript::Rank() const {
383   return std::visit(common::visitors{
384                         [](const IndirectSubscriptIntegerExpr &x) {
385                           return x.value().Rank();
386                         },
387                         [](const Triplet &) { return 1; },
388                     },
389       u);
390 }
391 
392 int ArrayRef::Rank() const {
393   int rank{0};
394   for (const auto &expr : subscript_) {
395     rank += expr.Rank();
396   }
397   if (rank > 0) {
398     return rank;
399   } else if (const Component * component{base_.UnwrapComponent()}) {
400     return component->base().Rank();
401   } else {
402     return 0;
403   }
404 }
405 
406 int CoarrayRef::Rank() const {
407   if (!subscript_.empty()) {
408     int rank{0};
409     for (const auto &expr : subscript_) {
410       rank += expr.Rank();
411     }
412     return rank;
413   } else {
414     return base_.back()->Rank();
415   }
416 }
417 
418 int DataRef::Rank() const {
419   return std::visit(common::visitors{
420                         [](SymbolRef symbol) { return symbol->Rank(); },
421                         [](const auto &x) { return x.Rank(); },
422                     },
423       u);
424 }
425 
426 int Substring::Rank() const {
427   return std::visit(common::visitors{
428                         [](const DataRef &dataRef) { return dataRef.Rank(); },
429                         [](const StaticDataObject::Pointer &) { return 0; },
430                     },
431       parent_);
432 }
433 
434 int ComplexPart::Rank() const { return complex_.Rank(); }
435 
436 template <typename T> int Designator<T>::Rank() const {
437   return std::visit(common::visitors{
438                         [](SymbolRef symbol) { return symbol->Rank(); },
439                         [](const auto &x) { return x.Rank(); },
440                     },
441       u);
442 }
443 
444 // GetBaseObject(), GetFirstSymbol(), GetLastSymbol(), &c.
445 const Symbol &Component::GetFirstSymbol() const {
446   return base_.value().GetFirstSymbol();
447 }
448 
449 const Symbol &NamedEntity::GetFirstSymbol() const {
450   return std::visit(common::visitors{
451                         [](SymbolRef s) -> const Symbol & { return s; },
452                         [](const Component &c) -> const Symbol & {
453                           return c.GetFirstSymbol();
454                         },
455                     },
456       u_);
457 }
458 
459 const Symbol &NamedEntity::GetLastSymbol() const {
460   return std::visit(common::visitors{
461                         [](SymbolRef s) -> const Symbol & { return s; },
462                         [](const Component &c) -> const Symbol & {
463                           return c.GetLastSymbol();
464                         },
465                     },
466       u_);
467 }
468 
469 const Component *NamedEntity::UnwrapComponent() const {
470   return std::visit(common::visitors{
471                         [](SymbolRef) -> const Component * { return nullptr; },
472                         [](const Component &c) { return &c; },
473                     },
474       u_);
475 }
476 
477 Component *NamedEntity::UnwrapComponent() {
478   return std::visit(common::visitors{
479                         [](SymbolRef &) -> Component * { return nullptr; },
480                         [](Component &c) { return &c; },
481                     },
482       u_);
483 }
484 
485 const Symbol &ArrayRef::GetFirstSymbol() const {
486   return base_.GetFirstSymbol();
487 }
488 
489 const Symbol &ArrayRef::GetLastSymbol() const { return base_.GetLastSymbol(); }
490 
491 const Symbol &DataRef::GetFirstSymbol() const {
492   return *std::visit(common::visitors{
493                          [](SymbolRef symbol) { return &*symbol; },
494                          [](const auto &x) { return &x.GetFirstSymbol(); },
495                      },
496       u);
497 }
498 
499 const Symbol &DataRef::GetLastSymbol() const {
500   return *std::visit(common::visitors{
501                          [](SymbolRef symbol) { return &*symbol; },
502                          [](const auto &x) { return &x.GetLastSymbol(); },
503                      },
504       u);
505 }
506 
507 BaseObject Substring::GetBaseObject() const {
508   return std::visit(common::visitors{
509                         [](const DataRef &dataRef) {
510                           return BaseObject{dataRef.GetFirstSymbol()};
511                         },
512                         [](StaticDataObject::Pointer pointer) {
513                           return BaseObject{std::move(pointer)};
514                         },
515                     },
516       parent_);
517 }
518 
519 const Symbol *Substring::GetLastSymbol() const {
520   return std::visit(
521       common::visitors{
522           [](const DataRef &dataRef) { return &dataRef.GetLastSymbol(); },
523           [](const auto &) -> const Symbol * { return nullptr; },
524       },
525       parent_);
526 }
527 
528 template <typename T> BaseObject Designator<T>::GetBaseObject() const {
529   return std::visit(
530       common::visitors{
531           [](SymbolRef symbol) { return BaseObject{symbol}; },
532           [](const Substring &sstring) { return sstring.GetBaseObject(); },
533           [](const auto &x) {
534 #if !__clang__ && __GNUC__ == 7 && __GNUC_MINOR__ == 2
535             if constexpr (std::is_same_v<std::decay_t<decltype(x)>,
536                               Substring>) {
537               return x.GetBaseObject();
538             } else
539 #endif
540               return BaseObject{x.GetFirstSymbol()};
541           },
542       },
543       u);
544 }
545 
546 template <typename T> const Symbol *Designator<T>::GetLastSymbol() const {
547   return std::visit(
548       common::visitors{
549           [](SymbolRef symbol) { return &*symbol; },
550           [](const Substring &sstring) { return sstring.GetLastSymbol(); },
551           [](const auto &x) {
552 #if !__clang__ && __GNUC__ == 7 && __GNUC_MINOR__ == 2
553             if constexpr (std::is_same_v<std::decay_t<decltype(x)>,
554                               Substring>) {
555               return x.GetLastSymbol();
556             } else
557 #endif
558               return &x.GetLastSymbol();
559           },
560       },
561       u);
562 }
563 
564 template <typename T>
565 std::optional<DynamicType> Designator<T>::GetType() const {
566   if constexpr (IsLengthlessIntrinsicType<Result>) {
567     return {Result::GetType()};
568   } else {
569     return DynamicType::From(GetLastSymbol());
570   }
571 }
572 
573 static NamedEntity AsNamedEntity(const SymbolVector &x) {
574   CHECK(!x.empty());
575   NamedEntity result{x.front()};
576   int j{0};
577   for (const Symbol &symbol : x) {
578     if (j++ != 0) {
579       DataRef base{result.IsSymbol() ? DataRef{result.GetLastSymbol()}
580                                      : DataRef{result.GetComponent()}};
581       result = NamedEntity{Component{std::move(base), symbol}};
582     }
583   }
584   return result;
585 }
586 
587 NamedEntity CoarrayRef::GetBase() const { return AsNamedEntity(base_); }
588 
589 // Equality testing
590 
591 // For the purposes of comparing type parameter expressions while
592 // testing the compatibility of procedure characteristics, two
593 // object dummy arguments with the same name are considered equal.
594 static bool AreSameSymbol(const Symbol &x, const Symbol &y) {
595   if (&x == &y) {
596     return true;
597   }
598   if (x.name() == y.name()) {
599     if (const auto *xObject{x.detailsIf<semantics::ObjectEntityDetails>()}) {
600       if (const auto *yObject{y.detailsIf<semantics::ObjectEntityDetails>()}) {
601         return xObject->isDummy() && yObject->isDummy();
602       }
603     }
604   }
605   return false;
606 }
607 
608 // Implements operator==() for a union type, using special case handling
609 // for Symbol references.
610 template <typename A> static bool TestVariableEquality(const A &x, const A &y) {
611   const SymbolRef *xSymbol{std::get_if<SymbolRef>(&x.u)};
612   if (const SymbolRef * ySymbol{std::get_if<SymbolRef>(&y.u)}) {
613     return xSymbol && AreSameSymbol(*xSymbol, *ySymbol);
614   } else {
615     return x.u == y.u;
616   }
617 }
618 
619 bool BaseObject::operator==(const BaseObject &that) const {
620   return TestVariableEquality(*this, that);
621 }
622 bool Component::operator==(const Component &that) const {
623   return base_ == that.base_ && &*symbol_ == &*that.symbol_;
624 }
625 bool NamedEntity::operator==(const NamedEntity &that) const {
626   if (IsSymbol()) {
627     return that.IsSymbol() &&
628         AreSameSymbol(GetFirstSymbol(), that.GetFirstSymbol());
629   } else {
630     return !that.IsSymbol() && GetComponent() == that.GetComponent();
631   }
632 }
633 template <int KIND>
634 bool TypeParamInquiry<KIND>::operator==(
635     const TypeParamInquiry<KIND> &that) const {
636   return &*parameter_ == &*that.parameter_ && base_ == that.base_;
637 }
638 bool Triplet::operator==(const Triplet &that) const {
639   return lower_ == that.lower_ && upper_ == that.upper_ &&
640       stride_ == that.stride_;
641 }
642 bool Subscript::operator==(const Subscript &that) const { return u == that.u; }
643 bool ArrayRef::operator==(const ArrayRef &that) const {
644   return base_ == that.base_ && subscript_ == that.subscript_;
645 }
646 bool CoarrayRef::operator==(const CoarrayRef &that) const {
647   return base_ == that.base_ && subscript_ == that.subscript_ &&
648       cosubscript_ == that.cosubscript_ && stat_ == that.stat_ &&
649       team_ == that.team_ && teamIsTeamNumber_ == that.teamIsTeamNumber_;
650 }
651 bool DataRef::operator==(const DataRef &that) const {
652   return TestVariableEquality(*this, that);
653 }
654 bool Substring::operator==(const Substring &that) const {
655   return parent_ == that.parent_ && lower_ == that.lower_ &&
656       upper_ == that.upper_;
657 }
658 bool ComplexPart::operator==(const ComplexPart &that) const {
659   return part_ == that.part_ && complex_ == that.complex_;
660 }
661 bool ProcedureRef::operator==(const ProcedureRef &that) const {
662   return proc_ == that.proc_ && arguments_ == that.arguments_;
663 }
664 template <typename T>
665 bool Designator<T>::operator==(const Designator<T> &that) const {
666   return TestVariableEquality(*this, that);
667 }
668 bool DescriptorInquiry::operator==(const DescriptorInquiry &that) const {
669   return field_ == that.field_ && base_ == that.base_ &&
670       dimension_ == that.dimension_;
671 }
672 
673 INSTANTIATE_VARIABLE_TEMPLATES
674 } // namespace Fortran::evaluate
675 
676 template class Fortran::common::Indirection<Fortran::evaluate::Component, true>;
677