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