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