FLANG
expression.h
1//===-- include/flang/Evaluate/expression.h ---------------------*- 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#ifndef FORTRAN_EVALUATE_EXPRESSION_H_
10#define FORTRAN_EVALUATE_EXPRESSION_H_
11
12// Represent Fortran expressions in a type-safe manner.
13// Expressions are the sole owners of their constituents; i.e., there is no
14// context-independent hash table or sharing of common subexpressions, and
15// thus these are trees, not DAGs. Both deep copy and move semantics are
16// supported for expression construction. Expressions may be compared
17// for equality.
18
19#include "common.h"
20#include "constant.h"
21#include "formatting.h"
22#include "type.h"
23#include "variable.h"
24#include "flang/Common/idioms.h"
25#include "flang/Common/indirection.h"
26#include "flang/Common/template.h"
27#include "flang/Parser/char-block.h"
28#include "flang/Support/Fortran.h"
29#include <algorithm>
30#include <tuple>
31#include <type_traits>
32#include <variant>
33
34namespace llvm {
35class raw_ostream;
36}
37
38namespace Fortran::evaluate {
39
40using common::LogicalOperator;
41using common::RelationalOperator;
42
43// Expressions are represented by specializations of the class template Expr.
44// Each of these specializations wraps a single data member "u" that
45// is a std::variant<> discriminated union over all of the representational
46// types for the constants, variables, operations, and other entities that
47// can be valid expressions in that context:
48// - Expr<Type<CATEGORY>> represents an expression whose result is of an
49// intrinsic type category, e.g. Type<TypeCategory::Real>, of any kind
50// - Expr<Type<TypeCategory::Derived>> wraps data and procedure references
51// that result in an instance of a derived type (or CLASS(*) unlimited
52// polymorphic)
53// - Expr<SomeType> is a union of Expr<Type<CATEGORY>> over all type
54// categories of Fortran. It represents any valid expression.
55//
56// Everything that can appear in, or as, a valid Fortran expression must be
57// represented with an instance of some class containing a Result typedef that
58// maps to some instantiation of Type<CATEGORY> or SomeType.
59// (Exception: BOZ literal constants in generic Expr<SomeType>.)
60template <typename A> using ResultType = typename std::decay_t<A>::Result;
61template <typename A> constexpr int ResultKind = std::decay_t<A>::kind();
62
63// Common Expr<> behaviors: every Expr<T> derives from ExpressionBase<T>.
64template <typename RESULT> class ExpressionBase {
65public:
66 using Result = RESULT;
67
68 int kind() const;
69
70private:
71 using Derived = Expr<Result>;
72#if defined(__APPLE__) && defined(__GNUC__)
73 Derived &derived();
74 const Derived &derived() const;
75#else
76 Derived &derived() { return *static_cast<Derived *>(this); }
77 const Derived &derived() const { return *static_cast<const Derived *>(this); }
78#endif
79
80public:
81 template <typename A> Derived &operator=(const A &x) {
82 Derived &d{derived()};
83 d.u = x;
84 return d;
85 }
86
87 template <typename A> common::IfNoLvalue<Derived &, A> operator=(A &&x) {
88 Derived &d{derived()};
89 d.u = std::move(x);
90 return d;
91 }
92
93 std::optional<DynamicType> GetType() const;
94 int Rank() const;
95 int Corank() const;
96 std::string AsFortran() const;
97#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
98 LLVM_DUMP_METHOD void dump() const;
99#endif
100 llvm::raw_ostream &AsFortran(llvm::raw_ostream &) const;
101 static Derived Rewrite(FoldingContext &, Derived &&);
102};
103
104// Operations always have specific Fortran result types (i.e., with known
105// intrinsic type category and kind parameter value). The classes that
106// represent the operations all inherit from this Operation<> base class
107// template. Note that Operation has as its first type parameter (DERIVED) a
108// "curiously recurring template pattern (CRTP)" reference to the specific
109// operation class being derived from Operation; e.g., Add is defined with
110// struct Add : public Operation<Add, ...>. Uses of instances of Operation<>,
111// including its own member functions, can access each specific class derived
112// from it via its derived() member function with compile-time type safety.
113template <typename DERIVED, typename RESULT, typename... OPERANDS>
114class Operation {
115 // The extra final member is a dummy that allows a safe unused reference
116 // to element 1 to arise indirectly in the definition of "right()" below
117 // when the operation has but a single operand.
118 using OperandTypes = std::tuple<OPERANDS..., std::monostate>;
119
120public:
121 using Derived = DERIVED;
122 using Result = RESULT;
123 static constexpr std::size_t operands{sizeof...(OPERANDS)};
124 // Allow specific intrinsic types and Parentheses<Type<TypeCategory::Derived>>
125 static_assert(IsSpecificIntrinsicType<Result> ||
126 (operands == 1 && std::is_same_v<Result, Type<TypeCategory::Derived>>));
127 template <int J> using Operand = std::tuple_element_t<J, OperandTypes>;
128
129 constexpr int kind() const { return kind_; }
130
131 // Unary operations wrap a single Expr with a CopyableIndirection.
132 // Binary operations wrap a tuple of CopyableIndirections to Exprs.
133private:
134 using Container = std::conditional_t<operands == 1,
135 common::CopyableIndirection<Expr<Operand<0>>>,
136 std::tuple<common::CopyableIndirection<Expr<OPERANDS>>...>>;
137
138public:
139 CLASS_BOILERPLATE(Operation)
140 explicit Operation(int kind, const Expr<OPERANDS> &...x)
141 : kind_{kind}, operand_{x...} {
142 CHECK_KIND(kind, RESULT);
143 }
144 explicit Operation(int kind, Expr<OPERANDS> &&...x)
145 : kind_{kind}, operand_{std::move(x)...} {
146 CHECK_KIND(kind, RESULT);
147 }
148
149 Derived &derived() { return *static_cast<Derived *>(this); }
150 const Derived &derived() const { return *static_cast<const Derived *>(this); }
151
152 // References to operand expressions from member functions of derived
153 // classes for specific operators can be made by index, e.g. operand<0>(),
154 // which must be spelled like "this->template operand<0>()" when
155 // inherited in a derived class template. There are convenience aliases
156 // left() and right() that are not templates.
157 template <int J> Expr<Operand<J>> &operand() {
158 if constexpr (operands == 1) {
159 static_assert(J == 0);
160 return operand_.value();
161 } else {
162 return std::get<J>(operand_).value();
163 }
164 }
165 template <int J> const Expr<Operand<J>> &operand() const {
166 if constexpr (operands == 1) {
167 static_assert(J == 0);
168 return operand_.value();
169 } else {
170 return std::get<J>(operand_).value();
171 }
172 }
173
174 Expr<Operand<0>> &left() { return operand<0>(); }
175 const Expr<Operand<0>> &left() const { return operand<0>(); }
176
177 std::conditional_t<(operands > 1), Expr<Operand<1>> &, void> right() {
178 if constexpr (operands > 1) {
179 return operand<1>();
180 }
181 }
182 std::conditional_t<(operands > 1), const Expr<Operand<1>> &, void>
183 right() const {
184 if constexpr (operands > 1) {
185 return operand<1>();
186 }
187 }
188
189 constexpr std::optional<DynamicType> GetType() const {
190 return DynamicType{Result::category, kind()};
191 }
192 int Rank() const {
193 int rank{left().Rank()};
194 if constexpr (operands > 1) {
195 return std::max(rank, right().Rank());
196 } else {
197 return rank;
198 }
199 }
200 static constexpr int Corank() { return 0; }
201
202 bool operator==(const Operation &that) const {
203 return kind() == that.kind() && operand_ == that.operand_;
204 }
205
206 llvm::raw_ostream &AsFortran(llvm::raw_ostream &) const;
207
208private:
209 int kind_;
210 Container operand_;
211};
212
213// Unary operations
214
215// Conversions to specific types from expressions of known category and
216// dynamic kind.
217template <typename TO, TypeCategory FROMCAT = TO::category>
218struct Convert : public Operation<Convert<TO, FROMCAT>, TO, Type<FROMCAT>> {
219 // Fortran doesn't have conversions between kinds of CHARACTER apart from
220 // assignments, and in those the data must be convertible to/from 7-bit ASCII.
221 static_assert(
222 ((TO::category == TypeCategory::Integer ||
223 TO::category == TypeCategory::Real ||
224 TO::category == TypeCategory::Unsigned) &&
225 (FROMCAT == TypeCategory::Integer || FROMCAT == TypeCategory::Real ||
226 FROMCAT == TypeCategory::Unsigned)) ||
227 TO::category == FROMCAT);
228 using Result = TO;
229 using Operand = Type<FROMCAT>;
230 using Base = Operation<Convert, Result, Operand>;
231 using Base::Base;
232 using Base::kind;
233 llvm::raw_ostream &AsFortran(llvm::raw_ostream &) const;
234};
235
236template <typename A>
237struct Parentheses : public Operation<Parentheses<A>, A, A> {
238 using Result = A;
239 using Operand = A;
240 using Base = Operation<Parentheses, A, A>;
241 using Base::Base;
242
243 explicit Parentheses(const Expr<A> &x) : Base{x.kind(), x} {}
244 explicit Parentheses(Expr<A> &&x) : Base{x.kind(), std::move(x)} {}
245};
246
247template <>
248struct Parentheses<Type<TypeCategory::Derived>>
249 : public Operation<Parentheses<Type<TypeCategory::Derived>>,
250 Type<TypeCategory::Derived>, Type<TypeCategory::Derived>> {
251public:
252 using Result = Type<TypeCategory::Derived>;
253 using Operand = Type<TypeCategory::Derived>;
254 using Base = Operation<Parentheses, Type<TypeCategory::Derived>,
256 using Base::Base;
257 DynamicType GetType() const;
258
259 explicit Parentheses(const Expr<Type<TypeCategory::Derived>> &x);
260 explicit Parentheses(Expr<Type<TypeCategory::Derived>> &&x);
261};
262
263template <typename A> struct Negate : public Operation<Negate<A>, A, A> {
264 using Result = A;
265 using Operand = A;
266 using Base = Operation<Negate, A, A>;
267 using Base::Base;
268
269 explicit Negate(const Expr<A> &x) : Base{x.kind(), x} {}
270 explicit Negate(Expr<A> &&x) : Base{x.kind(), std::move(x)} {}
271};
272
273struct ComplexComponent
274 : public Operation<ComplexComponent, Type<TypeCategory::Real>,
275 Type<TypeCategory::Complex>> {
276 using Result = Type<TypeCategory::Real>;
277 using Operand = Type<TypeCategory::Complex>;
278 using Base = Operation<ComplexComponent, Result, Operand>;
279 CLASS_BOILERPLATE(ComplexComponent)
280 ComplexComponent(bool isImaginary, const Expr<Operand> &x);
281 ComplexComponent(bool isImaginary, Expr<Operand> &&x);
282
283 bool isImaginaryPart{true};
284};
285
286struct Not : public Operation<Not, Type<TypeCategory::Logical>,
287 Type<TypeCategory::Logical>> {
288 using Result = Type<TypeCategory::Logical>;
289 using Operand = Result;
290 using Base = Operation<Not, Result, Operand>;
291 using Base::Base;
292};
293
294// Character lengths are determined by context in Fortran and do not
295// have explicit syntax for changing them. Expressions represent
296// changes of length (e.g., for assignments and structure constructors)
297// with this operation.
298struct SetLength : public Operation<SetLength, Type<TypeCategory::Character>,
299 Type<TypeCategory::Character>, SubscriptInteger> {
300 using Result = Type<TypeCategory::Character>;
301 using CharacterOperand = Result;
302 using LengthOperand = SubscriptInteger;
303 using Base = Operation<SetLength, Result, CharacterOperand, LengthOperand>;
304 using Base::Base;
305};
306
307// Binary operations
308
309template <typename A> struct Add : public Operation<Add<A>, A, A, A> {
310 using Result = A;
311 using Operand = A;
312 using Base = Operation<Add, A, A, A>;
313 using Base::Base;
314};
315
316template <typename A> struct Subtract : public Operation<Subtract<A>, A, A, A> {
317 using Result = A;
318 using Operand = A;
319 using Base = Operation<Subtract, A, A, A>;
320 using Base::Base;
321};
322
323template <typename A> struct Multiply : public Operation<Multiply<A>, A, A, A> {
324 using Result = A;
325 using Operand = A;
326 using Base = Operation<Multiply, A, A, A>;
327 using Base::Base;
328};
329
330template <typename A> struct Divide : public Operation<Divide<A>, A, A, A> {
331 using Result = A;
332 using Operand = A;
333 using Base = Operation<Divide, A, A, A>;
334 using Base::Base;
335};
336
337template <typename A> struct Power : public Operation<Power<A>, A, A, A> {
338 using Result = A;
339 using Operand = A;
340 using Base = Operation<Power, A, A, A>;
341 using Base::Base;
342};
343
344template <typename A>
346 : public Operation<RealToIntPower<A>, A, A, Type<TypeCategory::Integer>> {
347 using Base = Operation<RealToIntPower, A, A, Type<TypeCategory::Integer>>;
348 using Result = A;
349 using BaseOperand = A;
350 using ExponentOperand = Type<TypeCategory::Integer>;
351 using Base::Base;
352};
353
354template <typename A> struct Extremum : public Operation<Extremum<A>, A, A, A> {
355 using Result = A;
356 using Operand = A;
357 using Base = Operation<Extremum, A, A, A>;
358 CLASS_BOILERPLATE(Extremum)
359 Extremum(Ordering ord, const Expr<Operand> &x, const Expr<Operand> &y)
360 : Base{x.kind(), x, y}, ordering{ord} {
361 CHECK(x.kind() == y.kind());
362 }
363 Extremum(Ordering ord, Expr<Operand> &&x, Expr<Operand> &&y)
364 : Base{x.kind(), std::move(x), std::move(y)}, ordering{ord} {
365 CHECK(this->left().kind() == this->right().kind());
366 }
367 bool operator==(const Extremum &) const;
368 Ordering ordering{Ordering::Greater};
369};
370
371struct ComplexConstructor
372 : public Operation<ComplexConstructor, Type<TypeCategory::Complex>,
373 Type<TypeCategory::Real>, Type<TypeCategory::Real>> {
374 using Result = Type<TypeCategory::Complex>;
375 using Operand = Type<TypeCategory::Real>;
376 using Base = Operation<ComplexConstructor, Result, Operand, Operand>;
377 using Base::Base;
378
379 ComplexConstructor(const Expr<Type<TypeCategory::Real>> &re,
380 const Expr<Type<TypeCategory::Real>> &im);
381 ComplexConstructor(
383};
384
385struct Concat
386 : public Operation<Concat, Type<TypeCategory::Character>,
387 Type<TypeCategory::Character>, Type<TypeCategory::Character>> {
388 using Result = Type<TypeCategory::Character>;
389 using Operand = Result;
390 using Base = Operation<Concat, Result, Operand, Operand>;
391 using Base::Base;
392
393 Concat(const Expr<Type<TypeCategory::Character>> &x,
397};
398
399struct LogicalOperation
400 : public Operation<LogicalOperation, Type<TypeCategory::Logical>,
401 Type<TypeCategory::Logical>, Type<TypeCategory::Logical>> {
402 using Result = Type<TypeCategory::Logical>;
403 using Operand = Result;
404 using Base = Operation<LogicalOperation, Result, Operand, Operand>;
405 CLASS_BOILERPLATE(LogicalOperation)
406 LogicalOperation(
407 LogicalOperator opr, const Expr<Operand> &x, const Expr<Operand> &y);
408 LogicalOperation(LogicalOperator opr, Expr<Operand> &&x, Expr<Operand> &&y);
409 bool operator==(const LogicalOperation &) const;
410 LogicalOperator logicalOperator;
411};
412
413// Fortran 2023 conditional expression: (cond ? val : cond ? val : ... : else)
414// All branches have the same type and rank (verified during semantic analysis).
415template <typename T> class ConditionalExpr {
416public:
417 using Result = T;
418
419 constexpr int kind() const { return kind_; }
420
421 CLASS_BOILERPLATE(ConditionalExpr)
422 ConditionalExpr(Expr<LogicalResult> &&cond, Expr<Result> &&thenVal,
423 Expr<Result> &&elseVal)
424 : kind_{thenVal.kind()}, condition_{std::move(cond)},
425 thenValue_{std::move(thenVal)}, elseValue_{std::move(elseVal)} {
426 CHECK_KIND(kind(), Result);
427 CHECK(thenValue().kind() == elseValue().kind());
428 }
429 bool operator==(const ConditionalExpr &) const;
430 Expr<LogicalResult> &condition() { return condition_.value(); }
431 const Expr<LogicalResult> &condition() const { return condition_.value(); }
432 Expr<Result> &thenValue() { return thenValue_.value(); }
433 const Expr<Result> &thenValue() const { return thenValue_.value(); }
434 Expr<Result> &elseValue() { return elseValue_.value(); }
435 const Expr<Result> &elseValue() const { return elseValue_.value(); }
436 int Rank() const { return thenValue().Rank(); }
437 std::optional<DynamicType> GetType() const {
438 const auto thenType{thenValue().GetType()};
439 if constexpr (T::category == TypeCategory::Derived) {
440 // F2023 10.1.4(7) A conditional-expr is polymorphic if any branch is
441 if (thenType && !thenType->IsPolymorphic()) {
442 if (const auto elseType{elseValue().GetType()}) {
443 if (elseType->IsPolymorphic()) {
444 return elseType;
445 }
446 }
447 }
448 }
449 return thenType;
450 }
451 static constexpr int Corank() { return 0; }
452 llvm::raw_ostream &AsFortran(llvm::raw_ostream &) const;
453
454private:
455 int kind_;
456 common::CopyableIndirection<Expr<LogicalResult>> condition_;
457 common::CopyableIndirection<Expr<Result>> thenValue_;
458 common::CopyableIndirection<Expr<Result>> elseValue_;
459};
460
461// Array constructors
462template <typename RESULT> class ArrayConstructorValues;
463
465 using Result = SubscriptInteger;
466 bool operator==(const ImpliedDoIndex &) const;
467
468 static constexpr int kind() { return SubscriptIntegerKind; }
469
470 static constexpr DynamicType GetType() {
471 return {TypeCategory::Integer, kind()};
472 }
473 static constexpr int Rank() { return 0; }
474 static constexpr int Corank() { return 0; }
475 parser::CharBlock name; // nested implied DOs must use distinct names
476};
477
478template <typename RESULT> class ImpliedDo {
479public:
480 using Result = RESULT;
481 using Index = ResultType<ImpliedDoIndex>;
482 ImpliedDo(parser::CharBlock name, Expr<Index> &&lower, Expr<Index> &&upper,
484 : name_{name}, lower_{std::move(lower)}, upper_{std::move(upper)},
485 stride_{std::move(stride)}, values_{std::move(values)} {}
486 DEFAULT_CONSTRUCTORS_AND_ASSIGNMENTS(ImpliedDo)
487 bool operator==(const ImpliedDo &) const;
488 parser::CharBlock name() const { return name_; }
489 Expr<Index> &lower() { return lower_.value(); }
490 const Expr<Index> &lower() const { return lower_.value(); }
491 Expr<Index> &upper() { return upper_.value(); }
492 const Expr<Index> &upper() const { return upper_.value(); }
493 Expr<Index> &stride() { return stride_.value(); }
494 const Expr<Index> &stride() const { return stride_.value(); }
495 ArrayConstructorValues<Result> &values() { return values_.value(); }
496 const ArrayConstructorValues<Result> &values() const {
497 return values_.value();
498 }
499
500private:
501 parser::CharBlock name_;
502 common::CopyableIndirection<Expr<Index>> lower_, upper_, stride_;
503 common::CopyableIndirection<ArrayConstructorValues<Result>> values_;
504};
505
506template <typename RESULT> struct ArrayConstructorValue {
507 using Result = RESULT;
508 EVALUATE_UNION_CLASS_BOILERPLATE(ArrayConstructorValue)
509 std::variant<Expr<Result>, ImpliedDo<Result>> u;
510};
511
512template <typename RESULT> class ArrayConstructorValues {
513public:
514 using Result = RESULT;
515 using Values = std::vector<ArrayConstructorValue<Result>>;
516 DEFAULT_CONSTRUCTORS_AND_ASSIGNMENTS(ArrayConstructorValues)
517 ArrayConstructorValues() {}
518
519 bool operator==(const ArrayConstructorValues &) const;
520 static constexpr int Rank() { return 1; }
521 static constexpr int Corank() { return 0; }
522 template <typename A> common::NoLvalue<A> Push(A &&x) {
523 values_.emplace_back(std::move(x));
524 }
525
526 typename Values::iterator begin() { return values_.begin(); }
527 typename Values::const_iterator begin() const { return values_.begin(); }
528 typename Values::iterator end() { return values_.end(); }
529 typename Values::const_iterator end() const { return values_.end(); }
530
531protected:
532 Values values_;
533};
534
535// Note that there are specializations of ArrayConstructor for character
536// and derived types, since they must carry additional type information,
537// but that an empty ArrayConstructor can be constructed for any type
538// given an expression from which such type information may be gleaned.
539template <typename RESULT>
540class ArrayConstructor : public ArrayConstructorValues<RESULT> {
541public:
542 using Result = RESULT;
543 using Base = ArrayConstructorValues<Result>;
544
545 constexpr int kind() const { return kind_; }
546
547 DEFAULT_CONSTRUCTORS_AND_ASSIGNMENTS(ArrayConstructor)
548 explicit ArrayConstructor(int kind, Base &&values)
549 : Base{std::move(values)}, kind_{kind} {
550 CHECK_KIND(kind, RESULT);
551 }
552 template <typename T>
553 explicit ArrayConstructor(int kind, const Expr<T> &) : kind_{kind} {
554 CHECK_KIND(kind, RESULT);
555 }
556 static constexpr Result result(int kind) { return Result{kind}; }
557 DynamicType GetType() const { return {Result::category, kind_}; }
558 bool operator==(const ArrayConstructor &that) const {
559 return kind() == that.kind() && Base::operator==(that);
560 }
561 llvm::raw_ostream &AsFortran(llvm::raw_ostream &) const;
562
563private:
564 int kind_;
565};
566
567template <>
568class ArrayConstructor<Type<TypeCategory::Character>>
569 : public ArrayConstructorValues<Type<TypeCategory::Character>> {
570public:
571 using Result = Type<TypeCategory::Character>;
572 using Base = ArrayConstructorValues<Result>;
573
574 constexpr int kind() const { return kind_; }
575
576 DEFAULT_CONSTRUCTORS_AND_ASSIGNMENTS(ArrayConstructor)
577 explicit ArrayConstructor(int kind, Base &&values)
578 : Base{std::move(values)}, kind_{kind} {
579 CHECK_KIND(kind, Result);
580 }
581 template <typename T>
582 explicit ArrayConstructor(int kind, const Expr<T> &) : kind_{kind} {
583 CHECK_KIND(kind, Result);
584 }
585 ArrayConstructor &set_LEN(Expr<SubscriptInteger> &&);
586 bool operator==(const ArrayConstructor &) const;
587 static constexpr Result result(int kind) { return Result{kind}; }
588 DynamicType GetType() const { return {Result::category, kind()}; }
589 llvm::raw_ostream &AsFortran(llvm::raw_ostream &) const;
590 const Expr<SubscriptInteger> *LEN() const {
591 return length_ ? &length_->value() : nullptr;
592 }
593
594private:
595 int kind_;
596 std::optional<common::CopyableIndirection<Expr<SubscriptInteger>>> length_;
597};
598
599template <>
600class ArrayConstructor<Type<TypeCategory::Derived>>
601 : public ArrayConstructorValues<Type<TypeCategory::Derived>> {
602public:
603 using Result = Type<TypeCategory::Derived>;
604 using Base = ArrayConstructorValues<Result>;
605
606 static constexpr int kind() { return 0; }
607
608 CLASS_BOILERPLATE(ArrayConstructor)
609
610 ArrayConstructor(const semantics::DerivedTypeSpec &spec, Base &&v)
611 : Base{std::move(v)}, result_{spec} {}
612 template <typename A>
613 explicit ArrayConstructor(const A &prototype)
614 : result_{prototype.GetType().value().GetDerivedTypeSpec()} {}
615 template <typename A>
616 explicit ArrayConstructor(int kind, const A &prototype)
617 : result_{prototype.GetType().value().GetDerivedTypeSpec()} {
618 CHECK(kind == 0);
619 }
620
621 bool operator==(const ArrayConstructor &) const;
622 constexpr Result result() const { return result_; }
623 constexpr DynamicType GetType() const { return result_.GetType(); }
624 llvm::raw_ostream &AsFortran(llvm::raw_ostream &) const;
625
626private:
627 Result result_;
628};
629
630// Expression representations for each type category.
631
632template <>
633class Expr<Type<TypeCategory::Integer>>
634 : public ExpressionBase<Type<TypeCategory::Integer>> {
635public:
636 using Result = Type<TypeCategory::Integer>;
637
638 EVALUATE_UNION_CLASS_BOILERPLATE(Expr)
639
640private:
641 using Conversions = std::tuple<Convert<Result, TypeCategory::Integer>,
644 using Operations = std::tuple<Parentheses<Result>, Negate<Result>,
647 using Indices = std::tuple<ImpliedDoIndex>;
648 using TypeParamInquiries = std::tuple<TypeParamInquiry>;
649 using DescriptorInquiries = std::tuple<DescriptorInquiry>;
650 using RankOneBoundElements = std::tuple<RankOneBoundElement>;
651 using Others = std::tuple<Constant<Result>, ArrayConstructor<Result>,
653
654public:
655 common::TupleToVariant<common::CombineTuples<Operations, Conversions, Indices,
656 TypeParamInquiries, DescriptorInquiries, RankOneBoundElements, Others>>
657 u;
658};
659
660template <>
661class Expr<Type<TypeCategory::Unsigned>>
662 : public ExpressionBase<Type<TypeCategory::Unsigned>> {
663public:
664 using Result = Type<TypeCategory::Unsigned>;
665
666 EVALUATE_UNION_CLASS_BOILERPLATE(Expr)
667
668private:
669 using Conversions = std::tuple<Convert<Result, TypeCategory::Integer>,
672 using Operations = std::tuple<Parentheses<Result>, Negate<Result>,
675 using Others = std::tuple<Constant<Result>, ArrayConstructor<Result>,
677
678public:
679 common::TupleToVariant<common::CombineTuples<Operations, Conversions, Others>>
680 u;
681};
682
683template <>
684class Expr<Type<TypeCategory::Real>>
685 : public ExpressionBase<Type<TypeCategory::Real>> {
686public:
687 using Result = Type<TypeCategory::Real>;
688
689 EVALUATE_UNION_CLASS_BOILERPLATE(Expr)
690 explicit Expr(int kind, const Scalar<Result> &x)
691 : u{Constant<Result>{kind, x}} {}
692
693private:
694 // N.B. Real->Complex and Complex->Real conversions are done with CMPLX
695 // and part access operations (resp.).
696 using Conversions = std::variant<Convert<Result, TypeCategory::Integer>,
699 using Operations = std::variant<ComplexComponent, Parentheses<Result>,
703 using Others = std::variant<Constant<Result>, ArrayConstructor<Result>,
705
706public:
707 common::CombineVariants<Operations, Conversions, Others> u;
708};
709
710template <>
711class Expr<Type<TypeCategory::Complex>>
712 : public ExpressionBase<Type<TypeCategory::Complex>> {
713public:
714 using Result = Type<TypeCategory::Complex>;
715 EVALUATE_UNION_CLASS_BOILERPLATE(Expr)
716 explicit Expr(int kind, const Scalar<Result> &x)
717 : u{Constant<Result>{kind, x}} {}
718 using Operations = std::variant<Parentheses<Result>, Negate<Result>,
722 using Others = std::variant<Constant<Result>, ArrayConstructor<Result>,
724
725public:
726 common::CombineVariants<Operations, Others> u;
727};
728
729template <>
730class Expr<Type<TypeCategory::Character>>
731 : public ExpressionBase<Type<TypeCategory::Character>> {
732public:
733 using Result = Type<TypeCategory::Character>;
734 EVALUATE_UNION_CLASS_BOILERPLATE(Expr)
735 explicit Expr(int kind, const Scalar<Result> &x)
736 : u{Constant<Result>{kind, x}} {}
737 explicit Expr(int kind, Scalar<Result> &&x)
738 : u{Constant<Result>{kind, std::move(x)}} {}
739
740 std::optional<Expr<SubscriptInteger>> LEN() const;
741
742 std::variant<Constant<Result>, ArrayConstructor<Result>, Designator<Result>,
745 u;
746};
747
748// The Relational class template is a helper for constructing logical
749// expressions with polymorphism over the cross product of the possible
750// categories and kinds of comparable operands.
751// Fortran defines a numeric relation with distinct types or kinds as
752// first undergoing the same operand conversions that occur with the intrinsic
753// addition operator. Character relations must have the same kind.
754// There are no relations between LOGICAL values.
755
756template <typename T>
757class Relational : public Operation<Relational<T>, LogicalResult, T, T> {
758public:
759 using Result = LogicalResult;
760 using Base = Operation<Relational, LogicalResult, T, T>;
761 using Operand = typename Base::template Operand<0>;
762 static_assert(Operand::category == TypeCategory::Integer ||
763 Operand::category == TypeCategory::Real ||
764 Operand::category == TypeCategory::Complex ||
765 Operand::category == TypeCategory::Character ||
766 Operand::category == TypeCategory::Unsigned);
767 CLASS_BOILERPLATE(Relational)
768 Relational(
769 RelationalOperator r, const Expr<Operand> &a, const Expr<Operand> &b)
770 : Base{LogicalResultKind, a, b}, opr{r} {
771 CHECK(a.kind() == b.kind());
772 }
773 Relational(RelationalOperator r, Expr<Operand> &&a, Expr<Operand> &&b)
774 : Base{LogicalResultKind, std::move(a), std::move(b)}, opr{r} {
775 CHECK(this->left().kind() == this->right().kind());
776 }
777 static constexpr std::optional<DynamicType> GetType() {
778 return DynamicType{TypeCategory::Logical, LogicalResultKind};
779 }
780 bool operator==(const Relational &) const;
781 RelationalOperator opr;
782};
783
784template <> class Relational<SomeType> {
785 using DirectlyComparableTypes = common::CombineTuples<IntegerTypes, RealTypes,
786 ComplexTypes, CharacterTypes, UnsignedTypes>;
787
788public:
789 using Result = LogicalResult;
790 EVALUATE_UNION_CLASS_BOILERPLATE(Relational)
791 int kind() const {
792 return common::visit([](const auto &x) { return x.kind(); }, u);
793 }
794 static constexpr DynamicType GetType() {
795 return {TypeCategory::Logical, LogicalResultKind};
796 }
797 int Rank() const {
798 return common::visit([](const auto &x) { return x.Rank(); }, u);
799 }
800 static constexpr int Corank() { return 0; }
801 llvm::raw_ostream &AsFortran(llvm::raw_ostream &o) const;
802 common::MapTemplate<Relational, DirectlyComparableTypes> u;
803};
804
805extern template class Relational<Type<TypeCategory::Integer>>;
806extern template class Relational<Type<TypeCategory::Unsigned>>;
807extern template class Relational<Type<TypeCategory::Real>>;
808extern template class Relational<Type<TypeCategory::Character>>;
809
810// Relational<> operations always have the default logical result kind.
811// They are included in this shared runtime-kind variant, but report
812// LogicalResultKind from their kind() member.
813template <>
814class Expr<Type<TypeCategory::Logical>>
815 : public ExpressionBase<Type<TypeCategory::Logical>> {
816public:
817 using Result = Type<TypeCategory::Logical>;
818 EVALUATE_UNION_CLASS_BOILERPLATE(Expr)
819
820 explicit Expr(const Scalar<Result> &x) : u{Constant<Result>{x.kind(), x}} {}
821 explicit Expr(int kind, const Scalar<Result> &x)
822 : u{Constant<Result>{kind, x}} {}
823 explicit Expr(int kind, bool x)
824 : u{Constant<Result>{kind, Scalar<Result>{kind, x}}} {}
825
826private:
827 using Operations = std::tuple<Convert<Result>, Parentheses<Result>, Not,
829 using Relations = std::tuple<Relational<SomeType>>;
830 using Others = std::tuple<Constant<Result>, ArrayConstructor<Result>,
832
833public:
834 common::TupleToVariant<common::CombineTuples<Operations, Relations, Others>>
835 u;
836};
837
838// StructureConstructor pairs a StructureConstructorValues instance
839// (a map associating symbols with expressions) with a derived type
840// specification. There are two other similar classes:
841// - ArrayConstructor<Type<TypeCategory::Derived>> comprises a derived type
842// spec & zero or more instances of Expr<Type<TypeCategory::Derived>>; it has
843// rank 1 but not (in the most general case) a known shape.
844// - Constant<Type<TypeCategory::Derived>> comprises a derived type spec, zero
845// or more homogeneous instances of StructureConstructorValues whose type
846// parameters and component expressions are all constant, and a known shape
847// (possibly scalar).
848// StructureConstructor represents a scalar value of derived type that
849// is not necessarily a constant. It is used only as an
850// Expr<Type<TypeCategory::Derived>> alternative and as the type
851// Scalar<Type<TypeCategory::Derived>> (with an assumption of constant component
852// value expressions).
853class StructureConstructor {
854public:
855 using Result = Type<TypeCategory::Derived>;
856
857 static constexpr int kind() { return 0; }
858
859 explicit StructureConstructor(const semantics::DerivedTypeSpec &spec)
860 : result_{spec} {}
861 StructureConstructor(
862 const semantics::DerivedTypeSpec &, const StructureConstructorValues &);
863 StructureConstructor(
864 const semantics::DerivedTypeSpec &, StructureConstructorValues &&);
865 CLASS_BOILERPLATE(StructureConstructor)
866
867 constexpr Result result() const { return result_; }
868 const semantics::DerivedTypeSpec &derivedTypeSpec() const {
869 return result_.derivedTypeSpec();
870 }
871 StructureConstructorValues &values() { return values_; }
872 const StructureConstructorValues &values() const { return values_; }
873
874 bool operator==(const StructureConstructor &) const;
875
876 StructureConstructorValues::iterator begin() { return values_.begin(); }
877 StructureConstructorValues::const_iterator begin() const {
878 return values_.begin();
879 }
880 StructureConstructorValues::iterator end() { return values_.end(); }
881 StructureConstructorValues::const_iterator end() const {
882 return values_.end();
883 }
884
885 // can return nullopt
886 std::optional<Expr<SomeType>> Find(const Symbol &) const;
887
888 StructureConstructor &Add(const semantics::Symbol &, Expr<SomeType> &&);
889 static constexpr int Rank() { return 0; }
890 static constexpr int Corank() { return 0; }
891 DynamicType GetType() const;
892 llvm::raw_ostream &AsFortran(llvm::raw_ostream &) const;
893
894private:
895 std::optional<Expr<SomeType>> CreateParentComponent(const Symbol &) const;
896 Result result_;
897 StructureConstructorValues values_;
898};
899
900// An expression whose result has a derived type.
901template <>
902class Expr<Type<TypeCategory::Derived>>
903 : public ExpressionBase<Type<TypeCategory::Derived>> {
904public:
905 using Result = Type<TypeCategory::Derived>;
906 EVALUATE_UNION_CLASS_BOILERPLATE(Expr)
907 std::variant<Constant<Result>, ArrayConstructor<Result>, StructureConstructor,
910 u;
911};
912
913// A variant comprising the Expr<> instantiations over all type categories.
914using CategoryExpression = common::MapTemplate<Expr, SomeCategory>;
915
916// BOZ literal "typeless" constants must be wide enough to hold a numeric
917// value of any supported kind of INTEGER or REAL. They must also be
918// distinguishable from other integer constants, since they are permitted
919// to be used in only a few situations.
920using BOZLiteralConstant = typename LargestReal::Scalar::Word;
921inline constexpr int BOZLiteralConstantKind = LargestRealKind;
922
923// Null pointers without MOLD= arguments are typed by context.
925 static constexpr int kind() { return 0; }
926
927 constexpr bool operator==(const NullPointer &) const { return true; }
928 static constexpr int Rank() { return 0; }
929 static constexpr int Corank() { return 0; }
930};
931
932// Procedure pointer targets are treated as if they were typeless.
933// They are either procedure designators or values returned from
934// references to functions that return procedure (not object) pointers.
935using TypelessExpression = std::variant<BOZLiteralConstant, NullPointer,
937
938// A completely generic expression, polymorphic across all of the intrinsic type
939// categories and each of their kinds.
940template <> class Expr<SomeType> : public ExpressionBase<SomeType> {
941public:
942 using Result = SomeType;
943
944 static constexpr int kind() { return 0; }
945
946 EVALUATE_UNION_CLASS_BOILERPLATE(Expr)
947
948 // Owning references to these generic expressions can appear in other
949 // compiler data structures (viz., the parse tree and symbol table), so
950 // its destructor is externalized to reduce redundant default instances.
951 ~Expr();
952
953 common::CombineVariants<TypelessExpression, CategoryExpression> u;
954};
955
956// An assignment is either intrinsic, user-defined (with a ProcedureRef to
957// specify the procedure to call), or pointer assignment (with possibly empty
958// BoundsSpec or non-empty BoundsRemapping). In all cases there are Exprs
959// representing the LHS and RHS of the assignment.
960class Assignment {
961public:
962 Assignment(Expr<SomeType> &&lhs, Expr<SomeType> &&rhs)
963 : lhs(std::move(lhs)), rhs(std::move(rhs)) {}
964
965 struct Intrinsic {};
966 using BoundsSpec = std::vector<Expr<SubscriptInteger>>;
967 using BoundsRemapping =
968 std::vector<std::pair<Expr<SubscriptInteger>, Expr<SubscriptInteger>>>;
969 llvm::raw_ostream &AsFortran(llvm::raw_ostream &) const;
970
971 Expr<SomeType> lhs;
972 Expr<SomeType> rhs;
973 std::variant<Intrinsic, ProcedureRef, BoundsSpec, BoundsRemapping> u;
974};
975
976// This wrapper class is used, by means of a forward reference with
977// an owning pointer, to cache analyzed expressions in parse tree nodes.
978struct GenericExprWrapper {
979 GenericExprWrapper() {}
980 explicit GenericExprWrapper(std::optional<Expr<SomeType>> &&x)
981 : v{std::move(x)} {}
982 // The user-declared destructor would otherwise suppress these, and every
983 // "move" of a wrapper would deep-copy the expression.
984 GenericExprWrapper(GenericExprWrapper &&) = default;
985 GenericExprWrapper &operator=(GenericExprWrapper &&) = default;
986 ~GenericExprWrapper();
987 static void Deleter(GenericExprWrapper *);
988 std::optional<Expr<SomeType>> v; // vacant if error
989};
990
991// Like GenericExprWrapper but for analyzed assignments
992struct GenericAssignmentWrapper {
993 GenericAssignmentWrapper() {}
994 explicit GenericAssignmentWrapper(Assignment &&x) : v{std::move(x)} {}
995 explicit GenericAssignmentWrapper(std::optional<Assignment> &&x)
996 : v{std::move(x)} {}
997 GenericAssignmentWrapper(GenericAssignmentWrapper &&) = default;
998 GenericAssignmentWrapper &operator=(GenericAssignmentWrapper &&) = default;
999 ~GenericAssignmentWrapper();
1000 static void Deleter(GenericAssignmentWrapper *);
1001 std::optional<Assignment> v; // vacant if error
1002};
1003
1004FOR_EACH_TYPE_AND_KIND(extern template class ExpressionBase, )
1005FOR_EACH_INTRINSIC_KIND(extern template class ArrayConstructorValues, )
1006FOR_EACH_INTRINSIC_KIND(extern template class ArrayConstructor, )
1007
1008// Template instantiations to resolve these "extern template" declarations.
1009#define INSTANTIATE_EXPRESSION_TEMPLATES \
1010 template class Relational<Type<TypeCategory::Integer>>; \
1011 template class Relational<Type<TypeCategory::Unsigned>>; \
1012 template class Relational<Type<TypeCategory::Real>>; \
1013 template class Relational<Type<TypeCategory::Character>>; \
1014 FOR_EACH_TYPE_AND_KIND(template class ExpressionBase, ) \
1015 FOR_EACH_INTRINSIC_KIND(template class ArrayConstructorValues, ) \
1016 FOR_EACH_INTRINSIC_KIND(template class ArrayConstructor, ) \
1017 FOR_EACH_INTRINSIC_KIND(template class ConditionalExpr, )
1018
1019template <typename T>
1020inline Expr<T> MakeConstantExpr(int kind, const Scalar<T> &v) {
1021 CHECK(kind == v.kind());
1022 return Expr<T>{Constant<T>{kind, v}};
1023}
1024
1025template <typename T> inline Expr<T> MakeConstantExpr(int kind, Scalar<T> &&v) {
1026 CHECK(kind == v.kind());
1027 return Expr<T>{Constant<T>{kind, std::move(v)}};
1028}
1029
1030template <typename T>
1031inline Expr<T> MakeConstantExpr(int kind, const Constant<T> &c) {
1032 CHECK(kind == c.kind());
1033 return Expr<T>{c};
1034}
1035
1036template <typename T>
1037inline Expr<T> MakeConstantExpr(int kind, Constant<T> &&c) {
1038 CHECK(kind == c.kind());
1039 return Expr<T>{std::move(c)};
1040}
1041
1042template <typename T,
1043 typename =
1044 std::enable_if_t<std::is_same_v<T, Type<TypeCategory::Character>>>>
1045inline Expr<T> MakeConstantExpr(int kind, const std::string &v) {
1046 return Expr<T>{MakeConstant<T>(kind, v)};
1047}
1048
1049template <typename T,
1050 typename = std::enable_if_t<std::is_same_v<T, Type<TypeCategory::Integer>>>>
1051inline Expr<T> MakeConstantExpr(int kind, int64_t v) {
1052 return Expr<T>{Constant<T>{kind, Scalar<T>{kind, v}}};
1053}
1054
1055template <typename T,
1056 typename =
1057 std::enable_if_t<std::is_same_v<T, Type<TypeCategory::Unsigned>>>>
1058inline Expr<T> MakeConstantExpr(int kind, uint64_t v) {
1059 return Expr<T>{Constant<T>{kind, Scalar<T>{kind, v}}};
1060}
1061
1062template <typename T,
1063 typename = std::enable_if_t<std::is_same_v<T, Type<TypeCategory::Logical>>>>
1064inline Expr<T> MakeConstantExpr(int kind, bool v) {
1065 return Expr<T>{Constant<T>{kind, Scalar<T>{kind, v}}};
1066}
1067
1068template <typename T> inline Expr<T> MakeZeroExpr(int kind) {
1069 return MakeConstantExpr<T>(kind, Scalar<T>::Zero(kind));
1070}
1071
1072inline Expr<SubscriptInteger> MakeSubscriptIntExpr(int64_t v) {
1073 return Expr<SubscriptInteger>{MakeSubscriptIntConstant(v)};
1074}
1075
1076inline Expr<SubscriptInteger> MakeSubscriptIntExpr(
1077 const Scalar<SubscriptInteger> &v) {
1079 Constant<SubscriptInteger>{SubscriptIntegerKind, v}};
1080}
1081
1082inline Expr<SubscriptInteger> MakeSubscriptIntExpr(
1083 Scalar<SubscriptInteger> &&v) {
1085 Constant<SubscriptInteger>{SubscriptIntegerKind, std::move(v)}};
1086}
1087
1088// Subscripts, bounds, extents, and character lengths must have kind
1089// SubscriptIntegerKind; this is not enforced by their type.
1090inline bool IsSubscriptIntegerKind(const Expr<SubscriptInteger> &x) {
1091 return x.kind() == SubscriptIntegerKind;
1092}
1093inline bool IsSubscriptIntegerKind(
1094 const std::optional<Expr<SubscriptInteger>> &x) {
1095 return !x || IsSubscriptIntegerKind(*x);
1096}
1097
1098inline Expr<CInteger> MakeCIntegerExpr(int32_t v) {
1099 return Expr<CInteger>{MakeCIntegerConstant(v)};
1100}
1101
1102inline Expr<LogicalResult> MakeLogicalResultExpr(bool v) {
1103 return Expr<LogicalResult>{MakeLogicalResultConstant(v)};
1104}
1105
1106inline Expr<Ascii> MakeAsciiExpr(const std::string &v) {
1107 return Expr<Ascii>{MakeConstant<Ascii>(AsciiKind, v)};
1108}
1109
1110inline Expr<Ascii> MakeAsciiExpr(std::string &&v) {
1111 return Expr<Ascii>{MakeConstant<Ascii>(AsciiKind, std::move(v))};
1112}
1113
1114} // namespace Fortran::evaluate
1115#endif // FORTRAN_EVALUATE_EXPRESSION_H_
Definition expression.h:540
Definition expression.h:960
Definition expression.h:415
Definition constant.h:181
Definition variable.h:386
Definition type.h:101
Definition common.h:222
Definition expression.h:64
Definition common.h:224
Definition call.h:421
Definition expression.h:478
Definition call.h:356
Definition expression.h:757
Definition expression.h:853
Definition type.h:61
Definition char-block.h:27
Definition symbol.h:905
Definition call.h:34
Definition expression.h:309
Definition expression.h:506
Definition expression.h:965
Definition expression.h:373
Definition expression.h:387
Definition expression.h:218
Definition expression.h:330
Definition expression.h:354
Definition expression.h:464
Definition expression.h:401
Definition expression.h:323
Definition expression.h:263
Definition expression.h:287
Definition expression.h:924
Definition expression.h:237
Definition expression.h:337
Definition expression.h:346
Definition expression.h:299
Definition type.h:409
Definition expression.h:316