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