1 //===-- lib/Evaluate/characteristics.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/characteristics.h"
10 #include "flang/Common/indirection.h"
11 #include "flang/Evaluate/check-expression.h"
12 #include "flang/Evaluate/fold.h"
13 #include "flang/Evaluate/intrinsics.h"
14 #include "flang/Evaluate/tools.h"
15 #include "flang/Evaluate/type.h"
16 #include "flang/Parser/message.h"
17 #include "flang/Semantics/scope.h"
18 #include "flang/Semantics/symbol.h"
19 #include "llvm/Support/raw_ostream.h"
20 #include <initializer_list>
21 
22 using namespace Fortran::parser::literals;
23 
24 namespace Fortran::evaluate::characteristics {
25 
26 // Copy attributes from a symbol to dst based on the mapping in pairs.
27 template <typename A, typename B>
28 static void CopyAttrs(const semantics::Symbol &src, A &dst,
29     const std::initializer_list<std::pair<semantics::Attr, B>> &pairs) {
30   for (const auto &pair : pairs) {
31     if (src.attrs().test(pair.first)) {
32       dst.attrs.set(pair.second);
33     }
34   }
35 }
36 
37 // Shapes of function results and dummy arguments have to have
38 // the same rank, the same deferred dimensions, and the same
39 // values for explicit dimensions when constant.
40 bool ShapesAreCompatible(const Shape &x, const Shape &y) {
41   if (x.size() != y.size()) {
42     return false;
43   }
44   auto yIter{y.begin()};
45   for (const auto &xDim : x) {
46     const auto &yDim{*yIter++};
47     if (xDim) {
48       if (!yDim || ToInt64(*xDim) != ToInt64(*yDim)) {
49         return false;
50       }
51     } else if (yDim) {
52       return false;
53     }
54   }
55   return true;
56 }
57 
58 bool TypeAndShape::operator==(const TypeAndShape &that) const {
59   return type_ == that.type_ && ShapesAreCompatible(shape_, that.shape_) &&
60       attrs_ == that.attrs_ && corank_ == that.corank_;
61 }
62 
63 TypeAndShape &TypeAndShape::Rewrite(FoldingContext &context) {
64   LEN_ = Fold(context, std::move(LEN_));
65   shape_ = Fold(context, std::move(shape_));
66   return *this;
67 }
68 
69 std::optional<TypeAndShape> TypeAndShape::Characterize(
70     const semantics::Symbol &symbol, FoldingContext &context) {
71   const auto &ultimate{symbol.GetUltimate()};
72   return common::visit(
73       common::visitors{
74           [&](const semantics::ProcEntityDetails &proc) {
75             const semantics::ProcInterface &interface { proc.interface() };
76             if (interface.type()) {
77               return Characterize(*interface.type(), context);
78             } else if (interface.symbol()) {
79               return Characterize(*interface.symbol(), context);
80             } else {
81               return std::optional<TypeAndShape>{};
82             }
83           },
84           [&](const semantics::AssocEntityDetails &assoc) {
85             return Characterize(assoc, context);
86           },
87           [&](const semantics::ProcBindingDetails &binding) {
88             return Characterize(binding.symbol(), context);
89           },
90           [&](const auto &x) -> std::optional<TypeAndShape> {
91             using Ty = std::decay_t<decltype(x)>;
92             if constexpr (std::is_same_v<Ty, semantics::EntityDetails> ||
93                 std::is_same_v<Ty, semantics::ObjectEntityDetails> ||
94                 std::is_same_v<Ty, semantics::TypeParamDetails>) {
95               if (const semantics::DeclTypeSpec * type{ultimate.GetType()}) {
96                 if (auto dyType{DynamicType::From(*type)}) {
97                   TypeAndShape result{
98                       std::move(*dyType), GetShape(context, ultimate)};
99                   result.AcquireAttrs(ultimate);
100                   result.AcquireLEN(ultimate);
101                   return std::move(result.Rewrite(context));
102                 }
103               }
104             }
105             return std::nullopt;
106           },
107       },
108       // GetUltimate() used here, not ResolveAssociations(), because
109       // we need the type/rank of an associate entity from TYPE IS,
110       // CLASS IS, or RANK statement.
111       ultimate.details());
112 }
113 
114 std::optional<TypeAndShape> TypeAndShape::Characterize(
115     const semantics::AssocEntityDetails &assoc, FoldingContext &context) {
116   std::optional<TypeAndShape> result;
117   if (auto type{DynamicType::From(assoc.type())}) {
118     if (auto rank{assoc.rank()}) {
119       if (*rank >= 0 && *rank <= common::maxRank) {
120         result = TypeAndShape{std::move(*type), Shape(*rank)};
121       }
122     } else if (auto shape{GetShape(context, assoc.expr())}) {
123       result = TypeAndShape{std::move(*type), std::move(*shape)};
124     }
125     if (result && type->category() == TypeCategory::Character) {
126       if (const auto *chExpr{UnwrapExpr<Expr<SomeCharacter>>(assoc.expr())}) {
127         if (auto len{chExpr->LEN()}) {
128           result->set_LEN(std::move(*len));
129         }
130       }
131     }
132   }
133   return Fold(context, std::move(result));
134 }
135 
136 std::optional<TypeAndShape> TypeAndShape::Characterize(
137     const semantics::DeclTypeSpec &spec, FoldingContext &context) {
138   if (auto type{DynamicType::From(spec)}) {
139     return Fold(context, TypeAndShape{std::move(*type)});
140   } else {
141     return std::nullopt;
142   }
143 }
144 
145 std::optional<TypeAndShape> TypeAndShape::Characterize(
146     const ActualArgument &arg, FoldingContext &context) {
147   return Characterize(arg.UnwrapExpr(), context);
148 }
149 
150 bool TypeAndShape::IsCompatibleWith(parser::ContextualMessages &messages,
151     const TypeAndShape &that, const char *thisIs, const char *thatIs,
152     bool omitShapeConformanceCheck,
153     enum CheckConformanceFlags::Flags flags) const {
154   if (!type_.IsTkCompatibleWith(that.type_)) {
155     messages.Say(
156         "%1$s type '%2$s' is not compatible with %3$s type '%4$s'"_err_en_US,
157         thatIs, that.AsFortran(), thisIs, AsFortran());
158     return false;
159   }
160   return omitShapeConformanceCheck ||
161       CheckConformance(messages, shape_, that.shape_, flags, thisIs, thatIs)
162           .value_or(true /*fail only when nonconformance is known now*/);
163 }
164 
165 std::optional<Expr<SubscriptInteger>> TypeAndShape::MeasureElementSizeInBytes(
166     FoldingContext &foldingContext, bool align) const {
167   if (LEN_) {
168     CHECK(type_.category() == TypeCategory::Character);
169     return Fold(foldingContext,
170         Expr<SubscriptInteger>{type_.kind()} * Expr<SubscriptInteger>{*LEN_});
171   }
172   if (auto elementBytes{type_.MeasureSizeInBytes(foldingContext, align)}) {
173     return Fold(foldingContext, std::move(*elementBytes));
174   }
175   return std::nullopt;
176 }
177 
178 std::optional<Expr<SubscriptInteger>> TypeAndShape::MeasureSizeInBytes(
179     FoldingContext &foldingContext) const {
180   if (auto elements{GetSize(Shape{shape_})}) {
181     // Sizes of arrays (even with single elements) are multiples of
182     // their alignments.
183     if (auto elementBytes{
184             MeasureElementSizeInBytes(foldingContext, GetRank(shape_) > 0)}) {
185       return Fold(
186           foldingContext, std::move(*elements) * std::move(*elementBytes));
187     }
188   }
189   return std::nullopt;
190 }
191 
192 void TypeAndShape::AcquireAttrs(const semantics::Symbol &symbol) {
193   if (IsAssumedShape(symbol)) {
194     attrs_.set(Attr::AssumedShape);
195   }
196   if (IsDeferredShape(symbol)) {
197     attrs_.set(Attr::DeferredShape);
198   }
199   if (const auto *object{
200           symbol.GetUltimate().detailsIf<semantics::ObjectEntityDetails>()}) {
201     corank_ = object->coshape().Rank();
202     if (object->IsAssumedRank()) {
203       attrs_.set(Attr::AssumedRank);
204     }
205     if (object->IsAssumedSize()) {
206       attrs_.set(Attr::AssumedSize);
207     }
208     if (object->IsCoarray()) {
209       attrs_.set(Attr::Coarray);
210     }
211   }
212 }
213 
214 void TypeAndShape::AcquireLEN() {
215   if (auto len{type_.GetCharLength()}) {
216     LEN_ = std::move(len);
217   }
218 }
219 
220 void TypeAndShape::AcquireLEN(const semantics::Symbol &symbol) {
221   if (type_.category() == TypeCategory::Character) {
222     if (auto len{DataRef{symbol}.LEN()}) {
223       LEN_ = std::move(*len);
224     }
225   }
226 }
227 
228 std::string TypeAndShape::AsFortran() const {
229   return type_.AsFortran(LEN_ ? LEN_->AsFortran() : "");
230 }
231 
232 llvm::raw_ostream &TypeAndShape::Dump(llvm::raw_ostream &o) const {
233   o << type_.AsFortran(LEN_ ? LEN_->AsFortran() : "");
234   attrs_.Dump(o, EnumToString);
235   if (!shape_.empty()) {
236     o << " dimension";
237     char sep{'('};
238     for (const auto &expr : shape_) {
239       o << sep;
240       sep = ',';
241       if (expr) {
242         expr->AsFortran(o);
243       } else {
244         o << ':';
245       }
246     }
247     o << ')';
248   }
249   return o;
250 }
251 
252 bool DummyDataObject::operator==(const DummyDataObject &that) const {
253   return type == that.type && attrs == that.attrs && intent == that.intent &&
254       coshape == that.coshape;
255 }
256 
257 bool DummyDataObject::IsCompatibleWith(const DummyDataObject &actual) const {
258   return type.shape() == actual.type.shape() &&
259       type.type().IsTkCompatibleWith(actual.type.type()) &&
260       attrs == actual.attrs && intent == actual.intent &&
261       coshape == actual.coshape;
262 }
263 
264 static common::Intent GetIntent(const semantics::Attrs &attrs) {
265   if (attrs.test(semantics::Attr::INTENT_IN)) {
266     return common::Intent::In;
267   } else if (attrs.test(semantics::Attr::INTENT_OUT)) {
268     return common::Intent::Out;
269   } else if (attrs.test(semantics::Attr::INTENT_INOUT)) {
270     return common::Intent::InOut;
271   } else {
272     return common::Intent::Default;
273   }
274 }
275 
276 std::optional<DummyDataObject> DummyDataObject::Characterize(
277     const semantics::Symbol &symbol, FoldingContext &context) {
278   if (symbol.has<semantics::ObjectEntityDetails>() ||
279       symbol.has<semantics::EntityDetails>()) {
280     if (auto type{TypeAndShape::Characterize(symbol, context)}) {
281       std::optional<DummyDataObject> result{std::move(*type)};
282       using semantics::Attr;
283       CopyAttrs<DummyDataObject, DummyDataObject::Attr>(symbol, *result,
284           {
285               {Attr::OPTIONAL, DummyDataObject::Attr::Optional},
286               {Attr::ALLOCATABLE, DummyDataObject::Attr::Allocatable},
287               {Attr::ASYNCHRONOUS, DummyDataObject::Attr::Asynchronous},
288               {Attr::CONTIGUOUS, DummyDataObject::Attr::Contiguous},
289               {Attr::VALUE, DummyDataObject::Attr::Value},
290               {Attr::VOLATILE, DummyDataObject::Attr::Volatile},
291               {Attr::POINTER, DummyDataObject::Attr::Pointer},
292               {Attr::TARGET, DummyDataObject::Attr::Target},
293           });
294       result->intent = GetIntent(symbol.attrs());
295       return result;
296     }
297   }
298   return std::nullopt;
299 }
300 
301 bool DummyDataObject::CanBePassedViaImplicitInterface() const {
302   if ((attrs &
303           Attrs{Attr::Allocatable, Attr::Asynchronous, Attr::Optional,
304               Attr::Pointer, Attr::Target, Attr::Value, Attr::Volatile})
305           .any()) {
306     return false; // 15.4.2.2(3)(a)
307   } else if ((type.attrs() &
308                  TypeAndShape::Attrs{TypeAndShape::Attr::AssumedShape,
309                      TypeAndShape::Attr::AssumedRank,
310                      TypeAndShape::Attr::Coarray})
311                  .any()) {
312     return false; // 15.4.2.2(3)(b-d)
313   } else if (type.type().IsPolymorphic()) {
314     return false; // 15.4.2.2(3)(f)
315   } else if (const auto *derived{GetDerivedTypeSpec(type.type())}) {
316     return derived->parameters().empty(); // 15.4.2.2(3)(e)
317   } else {
318     return true;
319   }
320 }
321 
322 llvm::raw_ostream &DummyDataObject::Dump(llvm::raw_ostream &o) const {
323   attrs.Dump(o, EnumToString);
324   if (intent != common::Intent::Default) {
325     o << "INTENT(" << common::EnumToString(intent) << ')';
326   }
327   type.Dump(o);
328   if (!coshape.empty()) {
329     char sep{'['};
330     for (const auto &expr : coshape) {
331       expr.AsFortran(o << sep);
332       sep = ',';
333     }
334   }
335   return o;
336 }
337 
338 DummyProcedure::DummyProcedure(Procedure &&p)
339     : procedure{new Procedure{std::move(p)}} {}
340 
341 bool DummyProcedure::operator==(const DummyProcedure &that) const {
342   return attrs == that.attrs && intent == that.intent &&
343       procedure.value() == that.procedure.value();
344 }
345 
346 bool DummyProcedure::IsCompatibleWith(const DummyProcedure &actual) const {
347   return attrs == actual.attrs && intent == actual.intent &&
348       procedure.value().IsCompatibleWith(actual.procedure.value());
349 }
350 
351 static std::string GetSeenProcs(
352     const semantics::UnorderedSymbolSet &seenProcs) {
353   // Sort the symbols so that they appear in the same order on all platforms
354   auto ordered{semantics::OrderBySourcePosition(seenProcs)};
355   std::string result;
356   llvm::interleave(
357       ordered,
358       [&](const SymbolRef p) { result += '\'' + p->name().ToString() + '\''; },
359       [&]() { result += ", "; });
360   return result;
361 }
362 
363 // These functions with arguments of type UnorderedSymbolSet are used with
364 // mutually recursive calls when characterizing a Procedure, a DummyArgument,
365 // or a DummyProcedure to detect circularly defined procedures as required by
366 // 15.4.3.6, paragraph 2.
367 static std::optional<DummyArgument> CharacterizeDummyArgument(
368     const semantics::Symbol &symbol, FoldingContext &context,
369     semantics::UnorderedSymbolSet seenProcs);
370 static std::optional<FunctionResult> CharacterizeFunctionResult(
371     const semantics::Symbol &symbol, FoldingContext &context,
372     semantics::UnorderedSymbolSet seenProcs);
373 
374 static std::optional<Procedure> CharacterizeProcedure(
375     const semantics::Symbol &original, FoldingContext &context,
376     semantics::UnorderedSymbolSet seenProcs) {
377   Procedure result;
378   const auto &symbol{ResolveAssociations(original)};
379   if (seenProcs.find(symbol) != seenProcs.end()) {
380     std::string procsList{GetSeenProcs(seenProcs)};
381     context.messages().Say(symbol.name(),
382         "Procedure '%s' is recursively defined.  Procedures in the cycle:"
383         " %s"_err_en_US,
384         symbol.name(), procsList);
385     return std::nullopt;
386   }
387   seenProcs.insert(symbol);
388   CopyAttrs<Procedure, Procedure::Attr>(symbol, result,
389       {
390           {semantics::Attr::ELEMENTAL, Procedure::Attr::Elemental},
391           {semantics::Attr::BIND_C, Procedure::Attr::BindC},
392       });
393   if (IsPureProcedure(symbol) || // works for ENTRY too
394       (!symbol.attrs().test(semantics::Attr::IMPURE) &&
395           result.attrs.test(Procedure::Attr::Elemental))) {
396     result.attrs.set(Procedure::Attr::Pure);
397   }
398   return common::visit(
399       common::visitors{
400           [&](const semantics::SubprogramDetails &subp)
401               -> std::optional<Procedure> {
402             if (subp.isFunction()) {
403               if (auto fr{CharacterizeFunctionResult(
404                       subp.result(), context, seenProcs)}) {
405                 result.functionResult = std::move(fr);
406               } else {
407                 return std::nullopt;
408               }
409             } else {
410               result.attrs.set(Procedure::Attr::Subroutine);
411             }
412             for (const semantics::Symbol *arg : subp.dummyArgs()) {
413               if (!arg) {
414                 if (subp.isFunction()) {
415                   return std::nullopt;
416                 } else {
417                   result.dummyArguments.emplace_back(AlternateReturn{});
418                 }
419               } else if (auto argCharacteristics{CharacterizeDummyArgument(
420                              *arg, context, seenProcs)}) {
421                 result.dummyArguments.emplace_back(
422                     std::move(argCharacteristics.value()));
423               } else {
424                 return std::nullopt;
425               }
426             }
427             return result;
428           },
429           [&](const semantics::ProcEntityDetails &proc)
430               -> std::optional<Procedure> {
431             if (symbol.attrs().test(semantics::Attr::INTRINSIC)) {
432               // Fails when the intrinsic is not a specific intrinsic function
433               // from F'2018 table 16.2.  In order to handle forward references,
434               // attempts to use impermissible intrinsic procedures as the
435               // interfaces of procedure pointers are caught and flagged in
436               // declaration checking in Semantics.
437               auto intrinsic{context.intrinsics().IsSpecificIntrinsicFunction(
438                   symbol.name().ToString())};
439               if (intrinsic && intrinsic->isRestrictedSpecific) {
440                 intrinsic.reset(); // Exclude intrinsics from table 16.3.
441               }
442               return intrinsic;
443             }
444             const semantics::ProcInterface &interface { proc.interface() };
445             if (const semantics::Symbol * interfaceSymbol{interface.symbol()}) {
446               return CharacterizeProcedure(
447                   *interfaceSymbol, context, seenProcs);
448             } else {
449               result.attrs.set(Procedure::Attr::ImplicitInterface);
450               const semantics::DeclTypeSpec *type{interface.type()};
451               if (symbol.test(semantics::Symbol::Flag::Subroutine)) {
452                 // ignore any implicit typing
453                 result.attrs.set(Procedure::Attr::Subroutine);
454               } else if (type) {
455                 if (auto resultType{DynamicType::From(*type)}) {
456                   result.functionResult = FunctionResult{*resultType};
457                 } else {
458                   return std::nullopt;
459                 }
460               } else if (symbol.test(semantics::Symbol::Flag::Function)) {
461                 return std::nullopt;
462               }
463               // The PASS name, if any, is not a characteristic.
464               return result;
465             }
466           },
467           [&](const semantics::ProcBindingDetails &binding) {
468             if (auto result{CharacterizeProcedure(
469                     binding.symbol(), context, seenProcs)}) {
470               if (!symbol.attrs().test(semantics::Attr::NOPASS)) {
471                 auto passName{binding.passName()};
472                 for (auto &dummy : result->dummyArguments) {
473                   if (!passName || dummy.name.c_str() == *passName) {
474                     dummy.pass = true;
475                     return result;
476                   }
477                 }
478                 DIE("PASS argument missing");
479               }
480               return result;
481             } else {
482               return std::optional<Procedure>{};
483             }
484           },
485           [&](const semantics::UseDetails &use) {
486             return CharacterizeProcedure(use.symbol(), context, seenProcs);
487           },
488           [&](const semantics::HostAssocDetails &assoc) {
489             return CharacterizeProcedure(assoc.symbol(), context, seenProcs);
490           },
491           [&](const semantics::EntityDetails &) {
492             context.messages().Say(
493                 "Procedure '%s' is referenced before being sufficiently defined in a context where it must be so"_err_en_US,
494                 symbol.name());
495             return std::optional<Procedure>{};
496           },
497           [&](const semantics::SubprogramNameDetails &) {
498             context.messages().Say(
499                 "Procedure '%s' is referenced before being sufficiently defined in a context where it must be so"_err_en_US,
500                 symbol.name());
501             return std::optional<Procedure>{};
502           },
503           [&](const auto &) {
504             context.messages().Say(
505                 "'%s' is not a procedure"_err_en_US, symbol.name());
506             return std::optional<Procedure>{};
507           },
508       },
509       symbol.details());
510 }
511 
512 static std::optional<DummyProcedure> CharacterizeDummyProcedure(
513     const semantics::Symbol &symbol, FoldingContext &context,
514     semantics::UnorderedSymbolSet seenProcs) {
515   if (auto procedure{CharacterizeProcedure(symbol, context, seenProcs)}) {
516     // Dummy procedures may not be elemental.  Elemental dummy procedure
517     // interfaces are errors when the interface is not intrinsic, and that
518     // error is caught elsewhere.  Elemental intrinsic interfaces are
519     // made non-elemental.
520     procedure->attrs.reset(Procedure::Attr::Elemental);
521     DummyProcedure result{std::move(procedure.value())};
522     CopyAttrs<DummyProcedure, DummyProcedure::Attr>(symbol, result,
523         {
524             {semantics::Attr::OPTIONAL, DummyProcedure::Attr::Optional},
525             {semantics::Attr::POINTER, DummyProcedure::Attr::Pointer},
526         });
527     result.intent = GetIntent(symbol.attrs());
528     return result;
529   } else {
530     return std::nullopt;
531   }
532 }
533 
534 llvm::raw_ostream &DummyProcedure::Dump(llvm::raw_ostream &o) const {
535   attrs.Dump(o, EnumToString);
536   if (intent != common::Intent::Default) {
537     o << "INTENT(" << common::EnumToString(intent) << ')';
538   }
539   procedure.value().Dump(o);
540   return o;
541 }
542 
543 llvm::raw_ostream &AlternateReturn::Dump(llvm::raw_ostream &o) const {
544   return o << '*';
545 }
546 
547 DummyArgument::~DummyArgument() {}
548 
549 bool DummyArgument::operator==(const DummyArgument &that) const {
550   return u == that.u; // name and passed-object usage are not characteristics
551 }
552 
553 bool DummyArgument::IsCompatibleWith(const DummyArgument &actual) const {
554   if (const auto *ifaceData{std::get_if<DummyDataObject>(&u)}) {
555     const auto *actualData{std::get_if<DummyDataObject>(&actual.u)};
556     return actualData && ifaceData->IsCompatibleWith(*actualData);
557   } else if (const auto *ifaceProc{std::get_if<DummyProcedure>(&u)}) {
558     const auto *actualProc{std::get_if<DummyProcedure>(&actual.u)};
559     return actualProc && ifaceProc->IsCompatibleWith(*actualProc);
560   } else {
561     return std::holds_alternative<AlternateReturn>(u) &&
562         std::holds_alternative<AlternateReturn>(actual.u);
563   }
564 }
565 
566 static std::optional<DummyArgument> CharacterizeDummyArgument(
567     const semantics::Symbol &symbol, FoldingContext &context,
568     semantics::UnorderedSymbolSet seenProcs) {
569   auto name{symbol.name().ToString()};
570   if (symbol.has<semantics::ObjectEntityDetails>() ||
571       symbol.has<semantics::EntityDetails>()) {
572     if (auto obj{DummyDataObject::Characterize(symbol, context)}) {
573       return DummyArgument{std::move(name), std::move(obj.value())};
574     }
575   } else if (auto proc{
576                  CharacterizeDummyProcedure(symbol, context, seenProcs)}) {
577     return DummyArgument{std::move(name), std::move(proc.value())};
578   }
579   return std::nullopt;
580 }
581 
582 std::optional<DummyArgument> DummyArgument::FromActual(
583     std::string &&name, const Expr<SomeType> &expr, FoldingContext &context) {
584   return common::visit(
585       common::visitors{
586           [&](const BOZLiteralConstant &) {
587             return std::make_optional<DummyArgument>(std::move(name),
588                 DummyDataObject{
589                     TypeAndShape{DynamicType::TypelessIntrinsicArgument()}});
590           },
591           [&](const NullPointer &) {
592             return std::make_optional<DummyArgument>(std::move(name),
593                 DummyDataObject{
594                     TypeAndShape{DynamicType::TypelessIntrinsicArgument()}});
595           },
596           [&](const ProcedureDesignator &designator) {
597             if (auto proc{Procedure::Characterize(designator, context)}) {
598               return std::make_optional<DummyArgument>(
599                   std::move(name), DummyProcedure{std::move(*proc)});
600             } else {
601               return std::optional<DummyArgument>{};
602             }
603           },
604           [&](const ProcedureRef &call) {
605             if (auto proc{Procedure::Characterize(call, context)}) {
606               return std::make_optional<DummyArgument>(
607                   std::move(name), DummyProcedure{std::move(*proc)});
608             } else {
609               return std::optional<DummyArgument>{};
610             }
611           },
612           [&](const auto &) {
613             if (auto type{TypeAndShape::Characterize(expr, context)}) {
614               return std::make_optional<DummyArgument>(
615                   std::move(name), DummyDataObject{std::move(*type)});
616             } else {
617               return std::optional<DummyArgument>{};
618             }
619           },
620       },
621       expr.u);
622 }
623 
624 bool DummyArgument::IsOptional() const {
625   return common::visit(
626       common::visitors{
627           [](const DummyDataObject &data) {
628             return data.attrs.test(DummyDataObject::Attr::Optional);
629           },
630           [](const DummyProcedure &proc) {
631             return proc.attrs.test(DummyProcedure::Attr::Optional);
632           },
633           [](const AlternateReturn &) { return false; },
634       },
635       u);
636 }
637 
638 void DummyArgument::SetOptional(bool value) {
639   common::visit(common::visitors{
640                     [value](DummyDataObject &data) {
641                       data.attrs.set(DummyDataObject::Attr::Optional, value);
642                     },
643                     [value](DummyProcedure &proc) {
644                       proc.attrs.set(DummyProcedure::Attr::Optional, value);
645                     },
646                     [](AlternateReturn &) { DIE("cannot set optional"); },
647                 },
648       u);
649 }
650 
651 void DummyArgument::SetIntent(common::Intent intent) {
652   common::visit(common::visitors{
653                     [intent](DummyDataObject &data) { data.intent = intent; },
654                     [intent](DummyProcedure &proc) { proc.intent = intent; },
655                     [](AlternateReturn &) { DIE("cannot set intent"); },
656                 },
657       u);
658 }
659 
660 common::Intent DummyArgument::GetIntent() const {
661   return common::visit(
662       common::visitors{
663           [](const DummyDataObject &data) { return data.intent; },
664           [](const DummyProcedure &proc) { return proc.intent; },
665           [](const AlternateReturn &) -> common::Intent {
666             DIE("Alternate returns have no intent");
667           },
668       },
669       u);
670 }
671 
672 bool DummyArgument::CanBePassedViaImplicitInterface() const {
673   if (const auto *object{std::get_if<DummyDataObject>(&u)}) {
674     return object->CanBePassedViaImplicitInterface();
675   } else {
676     return true;
677   }
678 }
679 
680 bool DummyArgument::IsTypelessIntrinsicDummy() const {
681   const auto *argObj{std::get_if<characteristics::DummyDataObject>(&u)};
682   return argObj && argObj->type.type().IsTypelessIntrinsicArgument();
683 }
684 
685 llvm::raw_ostream &DummyArgument::Dump(llvm::raw_ostream &o) const {
686   if (!name.empty()) {
687     o << name << '=';
688   }
689   if (pass) {
690     o << " PASS";
691   }
692   common::visit([&](const auto &x) { x.Dump(o); }, u);
693   return o;
694 }
695 
696 FunctionResult::FunctionResult(DynamicType t) : u{TypeAndShape{t}} {}
697 FunctionResult::FunctionResult(TypeAndShape &&t) : u{std::move(t)} {}
698 FunctionResult::FunctionResult(Procedure &&p) : u{std::move(p)} {}
699 FunctionResult::~FunctionResult() {}
700 
701 bool FunctionResult::operator==(const FunctionResult &that) const {
702   return attrs == that.attrs && u == that.u;
703 }
704 
705 static std::optional<FunctionResult> CharacterizeFunctionResult(
706     const semantics::Symbol &symbol, FoldingContext &context,
707     semantics::UnorderedSymbolSet seenProcs) {
708   if (symbol.has<semantics::ObjectEntityDetails>()) {
709     if (auto type{TypeAndShape::Characterize(symbol, context)}) {
710       FunctionResult result{std::move(*type)};
711       CopyAttrs<FunctionResult, FunctionResult::Attr>(symbol, result,
712           {
713               {semantics::Attr::ALLOCATABLE, FunctionResult::Attr::Allocatable},
714               {semantics::Attr::CONTIGUOUS, FunctionResult::Attr::Contiguous},
715               {semantics::Attr::POINTER, FunctionResult::Attr::Pointer},
716           });
717       return result;
718     }
719   } else if (auto maybeProc{
720                  CharacterizeProcedure(symbol, context, seenProcs)}) {
721     FunctionResult result{std::move(*maybeProc)};
722     result.attrs.set(FunctionResult::Attr::Pointer);
723     return result;
724   }
725   return std::nullopt;
726 }
727 
728 std::optional<FunctionResult> FunctionResult::Characterize(
729     const Symbol &symbol, FoldingContext &context) {
730   semantics::UnorderedSymbolSet seenProcs;
731   return CharacterizeFunctionResult(symbol, context, seenProcs);
732 }
733 
734 bool FunctionResult::IsAssumedLengthCharacter() const {
735   if (const auto *ts{std::get_if<TypeAndShape>(&u)}) {
736     return ts->type().IsAssumedLengthCharacter();
737   } else {
738     return false;
739   }
740 }
741 
742 bool FunctionResult::CanBeReturnedViaImplicitInterface() const {
743   if (attrs.test(Attr::Pointer) || attrs.test(Attr::Allocatable)) {
744     return false; // 15.4.2.2(4)(b)
745   } else if (const auto *typeAndShape{GetTypeAndShape()}) {
746     if (typeAndShape->Rank() > 0) {
747       return false; // 15.4.2.2(4)(a)
748     } else {
749       const DynamicType &type{typeAndShape->type()};
750       switch (type.category()) {
751       case TypeCategory::Character:
752         if (type.knownLength()) {
753           return true;
754         } else if (const auto *param{type.charLengthParamValue()}) {
755           if (const auto &expr{param->GetExplicit()}) {
756             return IsConstantExpr(*expr); // 15.4.2.2(4)(c)
757           } else if (param->isAssumed()) {
758             return true;
759           }
760         }
761         return false;
762       case TypeCategory::Derived:
763         if (!type.IsPolymorphic()) {
764           const auto &spec{type.GetDerivedTypeSpec()};
765           for (const auto &pair : spec.parameters()) {
766             if (const auto &expr{pair.second.GetExplicit()}) {
767               if (!IsConstantExpr(*expr)) {
768                 return false; // 15.4.2.2(4)(c)
769               }
770             }
771           }
772           return true;
773         }
774         return false;
775       default:
776         return true;
777       }
778     }
779   } else {
780     return false; // 15.4.2.2(4)(b) - procedure pointer
781   }
782 }
783 
784 bool FunctionResult::IsCompatibleWith(const FunctionResult &actual) const {
785   Attrs actualAttrs{actual.attrs};
786   actualAttrs.reset(Attr::Contiguous);
787   if (attrs != actualAttrs) {
788     return false;
789   } else if (const auto *ifaceTypeShape{std::get_if<TypeAndShape>(&u)}) {
790     if (const auto *actualTypeShape{std::get_if<TypeAndShape>(&actual.u)}) {
791       if (ifaceTypeShape->Rank() != actualTypeShape->Rank()) {
792         return false;
793       } else if (!attrs.test(Attr::Allocatable) && !attrs.test(Attr::Pointer) &&
794           ifaceTypeShape->shape() != actualTypeShape->shape()) {
795         return false;
796       } else {
797         return ifaceTypeShape->type().IsTkCompatibleWith(
798             actualTypeShape->type());
799       }
800     } else {
801       return false;
802     }
803   } else {
804     const auto *ifaceProc{std::get_if<CopyableIndirection<Procedure>>(&u)};
805     if (const auto *actualProc{
806             std::get_if<CopyableIndirection<Procedure>>(&actual.u)}) {
807       return ifaceProc->value().IsCompatibleWith(actualProc->value());
808     } else {
809       return false;
810     }
811   }
812 }
813 
814 llvm::raw_ostream &FunctionResult::Dump(llvm::raw_ostream &o) const {
815   attrs.Dump(o, EnumToString);
816   common::visit(common::visitors{
817                     [&](const TypeAndShape &ts) { ts.Dump(o); },
818                     [&](const CopyableIndirection<Procedure> &p) {
819                       p.value().Dump(o << " procedure(") << ')';
820                     },
821                 },
822       u);
823   return o;
824 }
825 
826 Procedure::Procedure(FunctionResult &&fr, DummyArguments &&args, Attrs a)
827     : functionResult{std::move(fr)}, dummyArguments{std::move(args)}, attrs{a} {
828 }
829 Procedure::Procedure(DummyArguments &&args, Attrs a)
830     : dummyArguments{std::move(args)}, attrs{a} {}
831 Procedure::~Procedure() {}
832 
833 bool Procedure::operator==(const Procedure &that) const {
834   return attrs == that.attrs && functionResult == that.functionResult &&
835       dummyArguments == that.dummyArguments;
836 }
837 
838 bool Procedure::IsCompatibleWith(const Procedure &actual) const {
839   // 15.5.2.9(1): if dummy is not pure, actual need not be.
840   Attrs actualAttrs{actual.attrs};
841   if (!attrs.test(Attr::Pure)) {
842     actualAttrs.reset(Attr::Pure);
843   }
844   if (attrs != actualAttrs) {
845     return false;
846   } else if (IsFunction() != actual.IsFunction()) {
847     return false;
848   } else if (IsFunction() &&
849       !functionResult->IsCompatibleWith(*actual.functionResult)) {
850     return false;
851   } else if (dummyArguments.size() != actual.dummyArguments.size()) {
852     return false;
853   } else {
854     for (std::size_t j{0}; j < dummyArguments.size(); ++j) {
855       if (!dummyArguments[j].IsCompatibleWith(actual.dummyArguments[j])) {
856         return false;
857       }
858     }
859     return true;
860   }
861 }
862 
863 int Procedure::FindPassIndex(std::optional<parser::CharBlock> name) const {
864   int argCount{static_cast<int>(dummyArguments.size())};
865   int index{0};
866   if (name) {
867     while (index < argCount && *name != dummyArguments[index].name.c_str()) {
868       ++index;
869     }
870   }
871   CHECK(index < argCount);
872   return index;
873 }
874 
875 bool Procedure::CanOverride(
876     const Procedure &that, std::optional<int> passIndex) const {
877   // A pure procedure may override an impure one (7.5.7.3(2))
878   if ((that.attrs.test(Attr::Pure) && !attrs.test(Attr::Pure)) ||
879       that.attrs.test(Attr::Elemental) != attrs.test(Attr::Elemental) ||
880       functionResult != that.functionResult) {
881     return false;
882   }
883   int argCount{static_cast<int>(dummyArguments.size())};
884   if (argCount != static_cast<int>(that.dummyArguments.size())) {
885     return false;
886   }
887   for (int j{0}; j < argCount; ++j) {
888     if ((!passIndex || j != *passIndex) &&
889         dummyArguments[j] != that.dummyArguments[j]) {
890       return false;
891     }
892   }
893   return true;
894 }
895 
896 std::optional<Procedure> Procedure::Characterize(
897     const semantics::Symbol &original, FoldingContext &context) {
898   semantics::UnorderedSymbolSet seenProcs;
899   return CharacterizeProcedure(original, context, seenProcs);
900 }
901 
902 std::optional<Procedure> Procedure::Characterize(
903     const ProcedureDesignator &proc, FoldingContext &context) {
904   if (const auto *symbol{proc.GetSymbol()}) {
905     if (auto result{
906             characteristics::Procedure::Characterize(*symbol, context)}) {
907       return result;
908     }
909   } else if (const auto *intrinsic{proc.GetSpecificIntrinsic()}) {
910     return intrinsic->characteristics.value();
911   }
912   return std::nullopt;
913 }
914 
915 std::optional<Procedure> Procedure::Characterize(
916     const ProcedureRef &ref, FoldingContext &context) {
917   if (auto callee{Characterize(ref.proc(), context)}) {
918     if (callee->functionResult) {
919       if (const Procedure *
920           proc{callee->functionResult->IsProcedurePointer()}) {
921         return {*proc};
922       }
923     }
924   }
925   return std::nullopt;
926 }
927 
928 bool Procedure::CanBeCalledViaImplicitInterface() const {
929   // TODO: Pass back information on why we return false
930   if (attrs.test(Attr::Elemental) || attrs.test(Attr::BindC)) {
931     return false; // 15.4.2.2(5,6)
932   } else if (IsFunction() &&
933       !functionResult->CanBeReturnedViaImplicitInterface()) {
934     return false;
935   } else {
936     for (const DummyArgument &arg : dummyArguments) {
937       if (!arg.CanBePassedViaImplicitInterface()) {
938         return false;
939       }
940     }
941     return true;
942   }
943 }
944 
945 llvm::raw_ostream &Procedure::Dump(llvm::raw_ostream &o) const {
946   attrs.Dump(o, EnumToString);
947   if (functionResult) {
948     functionResult->Dump(o << "TYPE(") << ") FUNCTION";
949   } else {
950     o << "SUBROUTINE";
951   }
952   char sep{'('};
953   for (const auto &dummy : dummyArguments) {
954     dummy.Dump(o << sep);
955     sep = ',';
956   }
957   return o << (sep == '(' ? "()" : ")");
958 }
959 
960 // Utility class to determine if Procedures, etc. are distinguishable
961 class DistinguishUtils {
962 public:
963   explicit DistinguishUtils(const common::LanguageFeatureControl &features)
964       : features_{features} {}
965 
966   // Are these procedures distinguishable for a generic name?
967   bool Distinguishable(const Procedure &, const Procedure &) const;
968   // Are these procedures distinguishable for a generic operator or assignment?
969   bool DistinguishableOpOrAssign(const Procedure &, const Procedure &) const;
970 
971 private:
972   struct CountDummyProcedures {
973     CountDummyProcedures(const DummyArguments &args) {
974       for (const DummyArgument &arg : args) {
975         if (std::holds_alternative<DummyProcedure>(arg.u)) {
976           total += 1;
977           notOptional += !arg.IsOptional();
978         }
979       }
980     }
981     int total{0};
982     int notOptional{0};
983   };
984 
985   bool Rule3Distinguishable(const Procedure &, const Procedure &) const;
986   const DummyArgument *Rule1DistinguishingArg(
987       const DummyArguments &, const DummyArguments &) const;
988   int FindFirstToDistinguishByPosition(
989       const DummyArguments &, const DummyArguments &) const;
990   int FindLastToDistinguishByName(
991       const DummyArguments &, const DummyArguments &) const;
992   int CountCompatibleWith(const DummyArgument &, const DummyArguments &) const;
993   int CountNotDistinguishableFrom(
994       const DummyArgument &, const DummyArguments &) const;
995   bool Distinguishable(const DummyArgument &, const DummyArgument &) const;
996   bool Distinguishable(const DummyDataObject &, const DummyDataObject &) const;
997   bool Distinguishable(const DummyProcedure &, const DummyProcedure &) const;
998   bool Distinguishable(const FunctionResult &, const FunctionResult &) const;
999   bool Distinguishable(const TypeAndShape &, const TypeAndShape &) const;
1000   bool IsTkrCompatible(const DummyArgument &, const DummyArgument &) const;
1001   bool IsTkrCompatible(const TypeAndShape &, const TypeAndShape &) const;
1002   const DummyArgument *GetAtEffectivePosition(
1003       const DummyArguments &, int) const;
1004   const DummyArgument *GetPassArg(const Procedure &) const;
1005 
1006   const common::LanguageFeatureControl &features_;
1007 };
1008 
1009 // Simpler distinguishability rules for operators and assignment
1010 bool DistinguishUtils::DistinguishableOpOrAssign(
1011     const Procedure &proc1, const Procedure &proc2) const {
1012   auto &args1{proc1.dummyArguments};
1013   auto &args2{proc2.dummyArguments};
1014   if (args1.size() != args2.size()) {
1015     return true; // C1511: distinguishable based on number of arguments
1016   }
1017   for (std::size_t i{0}; i < args1.size(); ++i) {
1018     if (Distinguishable(args1[i], args2[i])) {
1019       return true; // C1511, C1512: distinguishable based on this arg
1020     }
1021   }
1022   return false;
1023 }
1024 
1025 bool DistinguishUtils::Distinguishable(
1026     const Procedure &proc1, const Procedure &proc2) const {
1027   auto &args1{proc1.dummyArguments};
1028   auto &args2{proc2.dummyArguments};
1029   auto count1{CountDummyProcedures(args1)};
1030   auto count2{CountDummyProcedures(args2)};
1031   if (count1.notOptional > count2.total || count2.notOptional > count1.total) {
1032     return true; // distinguishable based on C1514 rule 2
1033   }
1034   if (Rule3Distinguishable(proc1, proc2)) {
1035     return true; // distinguishable based on C1514 rule 3
1036   }
1037   if (Rule1DistinguishingArg(args1, args2)) {
1038     return true; // distinguishable based on C1514 rule 1
1039   }
1040   int pos1{FindFirstToDistinguishByPosition(args1, args2)};
1041   int name1{FindLastToDistinguishByName(args1, args2)};
1042   if (pos1 >= 0 && pos1 <= name1) {
1043     return true; // distinguishable based on C1514 rule 4
1044   }
1045   int pos2{FindFirstToDistinguishByPosition(args2, args1)};
1046   int name2{FindLastToDistinguishByName(args2, args1)};
1047   if (pos2 >= 0 && pos2 <= name2) {
1048     return true; // distinguishable based on C1514 rule 4
1049   }
1050   return false;
1051 }
1052 
1053 // C1514 rule 3: Procedures are distinguishable if both have a passed-object
1054 // dummy argument and those are distinguishable.
1055 bool DistinguishUtils::Rule3Distinguishable(
1056     const Procedure &proc1, const Procedure &proc2) const {
1057   const DummyArgument *pass1{GetPassArg(proc1)};
1058   const DummyArgument *pass2{GetPassArg(proc2)};
1059   return pass1 && pass2 && Distinguishable(*pass1, *pass2);
1060 }
1061 
1062 // Find a non-passed-object dummy data object in one of the argument lists
1063 // that satisfies C1514 rule 1. I.e. x such that:
1064 // - m is the number of dummy data objects in one that are nonoptional,
1065 //   are not passed-object, that x is TKR compatible with
1066 // - n is the number of non-passed-object dummy data objects, in the other
1067 //   that are not distinguishable from x
1068 // - m is greater than n
1069 const DummyArgument *DistinguishUtils::Rule1DistinguishingArg(
1070     const DummyArguments &args1, const DummyArguments &args2) const {
1071   auto size1{args1.size()};
1072   auto size2{args2.size()};
1073   for (std::size_t i{0}; i < size1 + size2; ++i) {
1074     const DummyArgument &x{i < size1 ? args1[i] : args2[i - size1]};
1075     if (!x.pass && std::holds_alternative<DummyDataObject>(x.u)) {
1076       if (CountCompatibleWith(x, args1) >
1077               CountNotDistinguishableFrom(x, args2) ||
1078           CountCompatibleWith(x, args2) >
1079               CountNotDistinguishableFrom(x, args1)) {
1080         return &x;
1081       }
1082     }
1083   }
1084   return nullptr;
1085 }
1086 
1087 // Find the index of the first nonoptional non-passed-object dummy argument
1088 // in args1 at an effective position such that either:
1089 // - args2 has no dummy argument at that effective position
1090 // - the dummy argument at that position is distinguishable from it
1091 int DistinguishUtils::FindFirstToDistinguishByPosition(
1092     const DummyArguments &args1, const DummyArguments &args2) const {
1093   int effective{0}; // position of arg1 in list, ignoring passed arg
1094   for (std::size_t i{0}; i < args1.size(); ++i) {
1095     const DummyArgument &arg1{args1.at(i)};
1096     if (!arg1.pass && !arg1.IsOptional()) {
1097       const DummyArgument *arg2{GetAtEffectivePosition(args2, effective)};
1098       if (!arg2 || Distinguishable(arg1, *arg2)) {
1099         return i;
1100       }
1101     }
1102     effective += !arg1.pass;
1103   }
1104   return -1;
1105 }
1106 
1107 // Find the index of the last nonoptional non-passed-object dummy argument
1108 // in args1 whose name is such that either:
1109 // - args2 has no dummy argument with that name
1110 // - the dummy argument with that name is distinguishable from it
1111 int DistinguishUtils::FindLastToDistinguishByName(
1112     const DummyArguments &args1, const DummyArguments &args2) const {
1113   std::map<std::string, const DummyArgument *> nameToArg;
1114   for (const auto &arg2 : args2) {
1115     nameToArg.emplace(arg2.name, &arg2);
1116   }
1117   for (int i = args1.size() - 1; i >= 0; --i) {
1118     const DummyArgument &arg1{args1.at(i)};
1119     if (!arg1.pass && !arg1.IsOptional()) {
1120       auto it{nameToArg.find(arg1.name)};
1121       if (it == nameToArg.end() || Distinguishable(arg1, *it->second)) {
1122         return i;
1123       }
1124     }
1125   }
1126   return -1;
1127 }
1128 
1129 // Count the dummy data objects in args that are nonoptional, are not
1130 // passed-object, and that x is TKR compatible with
1131 int DistinguishUtils::CountCompatibleWith(
1132     const DummyArgument &x, const DummyArguments &args) const {
1133   return std::count_if(args.begin(), args.end(), [&](const DummyArgument &y) {
1134     return !y.pass && !y.IsOptional() && IsTkrCompatible(x, y);
1135   });
1136 }
1137 
1138 // Return the number of dummy data objects in args that are not
1139 // distinguishable from x and not passed-object.
1140 int DistinguishUtils::CountNotDistinguishableFrom(
1141     const DummyArgument &x, const DummyArguments &args) const {
1142   return std::count_if(args.begin(), args.end(), [&](const DummyArgument &y) {
1143     return !y.pass && std::holds_alternative<DummyDataObject>(y.u) &&
1144         !Distinguishable(y, x);
1145   });
1146 }
1147 
1148 bool DistinguishUtils::Distinguishable(
1149     const DummyArgument &x, const DummyArgument &y) const {
1150   if (x.u.index() != y.u.index()) {
1151     return true; // different kind: data/proc/alt-return
1152   }
1153   return common::visit(
1154       common::visitors{
1155           [&](const DummyDataObject &z) {
1156             return Distinguishable(z, std::get<DummyDataObject>(y.u));
1157           },
1158           [&](const DummyProcedure &z) {
1159             return Distinguishable(z, std::get<DummyProcedure>(y.u));
1160           },
1161           [&](const AlternateReturn &) { return false; },
1162       },
1163       x.u);
1164 }
1165 
1166 bool DistinguishUtils::Distinguishable(
1167     const DummyDataObject &x, const DummyDataObject &y) const {
1168   using Attr = DummyDataObject::Attr;
1169   if (Distinguishable(x.type, y.type)) {
1170     return true;
1171   } else if (x.attrs.test(Attr::Allocatable) && y.attrs.test(Attr::Pointer) &&
1172       y.intent != common::Intent::In) {
1173     return true;
1174   } else if (y.attrs.test(Attr::Allocatable) && x.attrs.test(Attr::Pointer) &&
1175       x.intent != common::Intent::In) {
1176     return true;
1177   } else if (features_.IsEnabled(
1178                  common::LanguageFeature::DistinguishableSpecifics) &&
1179       (x.attrs.test(Attr::Allocatable) || x.attrs.test(Attr::Pointer)) &&
1180       (y.attrs.test(Attr::Allocatable) || y.attrs.test(Attr::Pointer)) &&
1181       (x.type.type().IsUnlimitedPolymorphic() !=
1182               y.type.type().IsUnlimitedPolymorphic() ||
1183           x.type.type().IsPolymorphic() != y.type.type().IsPolymorphic())) {
1184     // Extension: Per 15.5.2.5(2), an allocatable/pointer dummy and its
1185     // corresponding actual argument must both or neither be polymorphic,
1186     // and must both or neither be unlimited polymorphic.  So when exactly
1187     // one of two dummy arguments is polymorphic or unlimited polymorphic,
1188     // any actual argument that is admissible to one of them cannot also match
1189     // the other one.
1190     return true;
1191   } else {
1192     return false;
1193   }
1194 }
1195 
1196 bool DistinguishUtils::Distinguishable(
1197     const DummyProcedure &x, const DummyProcedure &y) const {
1198   const Procedure &xProc{x.procedure.value()};
1199   const Procedure &yProc{y.procedure.value()};
1200   if (Distinguishable(xProc, yProc)) {
1201     return true;
1202   } else {
1203     const std::optional<FunctionResult> &xResult{xProc.functionResult};
1204     const std::optional<FunctionResult> &yResult{yProc.functionResult};
1205     return xResult ? !yResult || Distinguishable(*xResult, *yResult)
1206                    : yResult.has_value();
1207   }
1208 }
1209 
1210 bool DistinguishUtils::Distinguishable(
1211     const FunctionResult &x, const FunctionResult &y) const {
1212   if (x.u.index() != y.u.index()) {
1213     return true; // one is data object, one is procedure
1214   }
1215   return common::visit(
1216       common::visitors{
1217           [&](const TypeAndShape &z) {
1218             return Distinguishable(z, std::get<TypeAndShape>(y.u));
1219           },
1220           [&](const CopyableIndirection<Procedure> &z) {
1221             return Distinguishable(z.value(),
1222                 std::get<CopyableIndirection<Procedure>>(y.u).value());
1223           },
1224       },
1225       x.u);
1226 }
1227 
1228 bool DistinguishUtils::Distinguishable(
1229     const TypeAndShape &x, const TypeAndShape &y) const {
1230   return !IsTkrCompatible(x, y) && !IsTkrCompatible(y, x);
1231 }
1232 
1233 // Compatibility based on type, kind, and rank
1234 bool DistinguishUtils::IsTkrCompatible(
1235     const DummyArgument &x, const DummyArgument &y) const {
1236   const auto *obj1{std::get_if<DummyDataObject>(&x.u)};
1237   const auto *obj2{std::get_if<DummyDataObject>(&y.u)};
1238   return obj1 && obj2 && IsTkrCompatible(obj1->type, obj2->type);
1239 }
1240 bool DistinguishUtils::IsTkrCompatible(
1241     const TypeAndShape &x, const TypeAndShape &y) const {
1242   return x.type().IsTkCompatibleWith(y.type()) &&
1243       (x.attrs().test(TypeAndShape::Attr::AssumedRank) ||
1244           y.attrs().test(TypeAndShape::Attr::AssumedRank) ||
1245           x.Rank() == y.Rank());
1246 }
1247 
1248 // Return the argument at the given index, ignoring the passed arg
1249 const DummyArgument *DistinguishUtils::GetAtEffectivePosition(
1250     const DummyArguments &args, int index) const {
1251   for (const DummyArgument &arg : args) {
1252     if (!arg.pass) {
1253       if (index == 0) {
1254         return &arg;
1255       }
1256       --index;
1257     }
1258   }
1259   return nullptr;
1260 }
1261 
1262 // Return the passed-object dummy argument of this procedure, if any
1263 const DummyArgument *DistinguishUtils::GetPassArg(const Procedure &proc) const {
1264   for (const auto &arg : proc.dummyArguments) {
1265     if (arg.pass) {
1266       return &arg;
1267     }
1268   }
1269   return nullptr;
1270 }
1271 
1272 bool Distinguishable(const common::LanguageFeatureControl &features,
1273     const Procedure &x, const Procedure &y) {
1274   return DistinguishUtils{features}.Distinguishable(x, y);
1275 }
1276 
1277 bool DistinguishableOpOrAssign(const common::LanguageFeatureControl &features,
1278     const Procedure &x, const Procedure &y) {
1279   return DistinguishUtils{features}.DistinguishableOpOrAssign(x, y);
1280 }
1281 
1282 DEFINE_DEFAULT_CONSTRUCTORS_AND_ASSIGNMENTS(DummyArgument)
1283 DEFINE_DEFAULT_CONSTRUCTORS_AND_ASSIGNMENTS(DummyProcedure)
1284 DEFINE_DEFAULT_CONSTRUCTORS_AND_ASSIGNMENTS(FunctionResult)
1285 DEFINE_DEFAULT_CONSTRUCTORS_AND_ASSIGNMENTS(Procedure)
1286 } // namespace Fortran::evaluate::characteristics
1287 
1288 template class Fortran::common::Indirection<
1289     Fortran::evaluate::characteristics::Procedure, true>;
1290