1 //===-- lib/Semantics/semantics.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/Semantics/semantics.h" 10 #include "assignment.h" 11 #include "canonicalize-acc.h" 12 #include "canonicalize-do.h" 13 #include "canonicalize-omp.h" 14 #include "check-acc-structure.h" 15 #include "check-allocate.h" 16 #include "check-arithmeticif.h" 17 #include "check-case.h" 18 #include "check-coarray.h" 19 #include "check-data.h" 20 #include "check-deallocate.h" 21 #include "check-declarations.h" 22 #include "check-do-forall.h" 23 #include "check-if-stmt.h" 24 #include "check-io.h" 25 #include "check-namelist.h" 26 #include "check-nullify.h" 27 #include "check-omp-structure.h" 28 #include "check-purity.h" 29 #include "check-return.h" 30 #include "check-select-rank.h" 31 #include "check-select-type.h" 32 #include "check-stop.h" 33 #include "compute-offsets.h" 34 #include "mod-file.h" 35 #include "resolve-labels.h" 36 #include "resolve-names.h" 37 #include "rewrite-parse-tree.h" 38 #include "flang/Common/default-kinds.h" 39 #include "flang/Parser/parse-tree-visitor.h" 40 #include "flang/Parser/tools.h" 41 #include "flang/Semantics/expression.h" 42 #include "flang/Semantics/scope.h" 43 #include "flang/Semantics/symbol.h" 44 #include "llvm/Support/raw_ostream.h" 45 46 namespace Fortran::semantics { 47 48 using NameToSymbolMap = std::multimap<parser::CharBlock, SymbolRef>; 49 static void DoDumpSymbols(llvm::raw_ostream &, const Scope &, int indent = 0); 50 static void PutIndent(llvm::raw_ostream &, int indent); 51 52 static void GetSymbolNames(const Scope &scope, NameToSymbolMap &symbols) { 53 // Finds all symbol names in the scope without collecting duplicates. 54 for (const auto &pair : scope) { 55 symbols.emplace(pair.second->name(), *pair.second); 56 } 57 for (const auto &pair : scope.commonBlocks()) { 58 symbols.emplace(pair.second->name(), *pair.second); 59 } 60 for (const auto &child : scope.children()) { 61 GetSymbolNames(child, symbols); 62 } 63 } 64 65 // A parse tree visitor that calls Enter/Leave functions from each checker 66 // class C supplied as template parameters. Enter is called before the node's 67 // children are visited, Leave is called after. No two checkers may have the 68 // same Enter or Leave function. Each checker must be constructible from 69 // SemanticsContext and have BaseChecker as a virtual base class. 70 template <typename... C> class SemanticsVisitor : public virtual C... { 71 public: 72 using C::Enter...; 73 using C::Leave...; 74 using BaseChecker::Enter; 75 using BaseChecker::Leave; 76 SemanticsVisitor(SemanticsContext &context) 77 : C{context}..., context_{context} {} 78 79 template <typename N> bool Pre(const N &node) { 80 if constexpr (common::HasMember<const N *, ConstructNode>) { 81 context_.PushConstruct(node); 82 } 83 Enter(node); 84 return true; 85 } 86 template <typename N> void Post(const N &node) { 87 Leave(node); 88 if constexpr (common::HasMember<const N *, ConstructNode>) { 89 context_.PopConstruct(); 90 } 91 } 92 93 template <typename T> bool Pre(const parser::Statement<T> &node) { 94 context_.set_location(node.source); 95 Enter(node); 96 return true; 97 } 98 template <typename T> bool Pre(const parser::UnlabeledStatement<T> &node) { 99 context_.set_location(node.source); 100 Enter(node); 101 return true; 102 } 103 template <typename T> void Post(const parser::Statement<T> &node) { 104 Leave(node); 105 context_.set_location(std::nullopt); 106 } 107 template <typename T> void Post(const parser::UnlabeledStatement<T> &node) { 108 Leave(node); 109 context_.set_location(std::nullopt); 110 } 111 112 bool Walk(const parser::Program &program) { 113 parser::Walk(program, *this); 114 return !context_.AnyFatalError(); 115 } 116 117 private: 118 SemanticsContext &context_; 119 }; 120 121 class MiscChecker : public virtual BaseChecker { 122 public: 123 explicit MiscChecker(SemanticsContext &context) : context_{context} {} 124 void Leave(const parser::EntryStmt &) { 125 if (!context_.constructStack().empty()) { // C1571 126 context_.Say("ENTRY may not appear in an executable construct"_err_en_US); 127 } 128 } 129 void Leave(const parser::AssignStmt &stmt) { 130 CheckAssignGotoName(std::get<parser::Name>(stmt.t)); 131 } 132 void Leave(const parser::AssignedGotoStmt &stmt) { 133 CheckAssignGotoName(std::get<parser::Name>(stmt.t)); 134 } 135 136 private: 137 void CheckAssignGotoName(const parser::Name &name) { 138 if (context_.HasError(name.symbol)) { 139 return; 140 } 141 const Symbol &symbol{DEREF(name.symbol)}; 142 auto type{evaluate::DynamicType::From(symbol)}; 143 if (!IsVariableName(symbol) || symbol.Rank() != 0 || !type || 144 type->category() != TypeCategory::Integer || 145 type->kind() != 146 context_.defaultKinds().GetDefaultKind(TypeCategory::Integer)) { 147 context_ 148 .Say(name.source, 149 "'%s' must be a default integer scalar variable"_err_en_US, 150 name.source) 151 .Attach(symbol.name(), "Declaration of '%s'"_en_US, symbol.name()); 152 } 153 } 154 155 SemanticsContext &context_; 156 }; 157 158 using StatementSemanticsPass1 = ExprChecker; 159 using StatementSemanticsPass2 = SemanticsVisitor<AccStructureChecker, 160 AllocateChecker, ArithmeticIfStmtChecker, AssignmentChecker, CaseChecker, 161 CoarrayChecker, DataChecker, DeallocateChecker, DoForallChecker, 162 IfStmtChecker, IoChecker, MiscChecker, NamelistChecker, NullifyChecker, 163 OmpStructureChecker, PurityChecker, ReturnStmtChecker, 164 SelectRankConstructChecker, SelectTypeChecker, StopChecker>; 165 166 static bool PerformStatementSemantics( 167 SemanticsContext &context, parser::Program &program) { 168 ResolveNames(context, program, context.globalScope()); 169 RewriteParseTree(context, program); 170 ComputeOffsets(context, context.globalScope()); 171 CheckDeclarations(context); 172 StatementSemanticsPass1{context}.Walk(program); 173 StatementSemanticsPass2 pass2{context}; 174 pass2.Walk(program); 175 if (!context.AnyFatalError()) { 176 pass2.CompileDataInitializationsIntoInitializers(); 177 } 178 return !context.AnyFatalError(); 179 } 180 181 /// This class keeps track of the common block appearances with the biggest size 182 /// and with an initial value (if any) in a program. This allows reporting 183 /// conflicting initialization and warning about appearances of a same 184 /// named common block with different sizes. The biggest common block size and 185 /// initialization (if any) can later be provided so that lowering can generate 186 /// the correct symbol size and initial values, even when named common blocks 187 /// appears with different sizes and are initialized outside of block data. 188 class CommonBlockMap { 189 private: 190 struct CommonBlockInfo { 191 // Common block symbol for the appearance with the biggest size. 192 SymbolRef biggestSize; 193 // Common block symbol for the appearance with the initialized members (if 194 // any). 195 std::optional<SymbolRef> initialization; 196 }; 197 198 public: 199 void MapCommonBlockAndCheckConflicts( 200 SemanticsContext &context, const Symbol &common) { 201 const Symbol *isInitialized{CommonBlockIsInitialized(common)}; 202 auto [it, firstAppearance] = commonBlocks_.insert({common.name(), 203 isInitialized ? CommonBlockInfo{common, common} 204 : CommonBlockInfo{common, std::nullopt}}); 205 if (!firstAppearance) { 206 CommonBlockInfo &info{it->second}; 207 if (isInitialized) { 208 if (info.initialization.has_value() && 209 &**info.initialization != &common) { 210 // Use the location of the initialization in the error message because 211 // common block symbols may have no location if they are blank 212 // commons. 213 const Symbol &previousInit{ 214 DEREF(CommonBlockIsInitialized(**info.initialization))}; 215 context 216 .Say(isInitialized->name(), 217 "Multiple initialization of COMMON block /%s/"_err_en_US, 218 common.name()) 219 .Attach(previousInit.name(), 220 "Previous initialization of COMMON block /%s/"_en_US, 221 common.name()); 222 } else { 223 info.initialization = common; 224 } 225 } 226 if (common.size() != info.biggestSize->size() && !common.name().empty()) { 227 context 228 .Say(common.name(), 229 "A named COMMON block should have the same size everywhere it appears (%zd bytes here)"_port_en_US, 230 common.size()) 231 .Attach(info.biggestSize->name(), 232 "Previously defined with a size of %zd bytes"_en_US, 233 info.biggestSize->size()); 234 } 235 if (common.size() > info.biggestSize->size()) { 236 info.biggestSize = common; 237 } 238 } 239 } 240 241 CommonBlockList GetCommonBlocks() const { 242 CommonBlockList result; 243 for (const auto &[_, blockInfo] : commonBlocks_) { 244 result.emplace_back( 245 std::make_pair(blockInfo.initialization ? *blockInfo.initialization 246 : blockInfo.biggestSize, 247 blockInfo.biggestSize->size())); 248 } 249 return result; 250 } 251 252 private: 253 /// Return the symbol of an initialized member if a COMMON block 254 /// is initalized. Otherwise, return nullptr. 255 static Symbol *CommonBlockIsInitialized(const Symbol &common) { 256 const auto &commonDetails = 257 common.get<Fortran::semantics::CommonBlockDetails>(); 258 259 for (const auto &member : commonDetails.objects()) { 260 if (IsInitialized(*member)) { 261 return &*member; 262 } 263 } 264 265 // Common block may be initialized via initialized variables that are in an 266 // equivalence with the common block members. 267 for (const Fortran::semantics::EquivalenceSet &set : 268 common.owner().equivalenceSets()) { 269 for (const Fortran::semantics::EquivalenceObject &obj : set) { 270 if (!obj.symbol.test( 271 Fortran::semantics::Symbol::Flag::CompilerCreated)) { 272 if (FindCommonBlockContaining(obj.symbol) == &common && 273 IsInitialized(obj.symbol)) { 274 return &obj.symbol; 275 } 276 } 277 } 278 } 279 return nullptr; 280 } 281 std::map<SourceName, CommonBlockInfo> commonBlocks_; 282 }; 283 284 SemanticsContext::SemanticsContext( 285 const common::IntrinsicTypeDefaultKinds &defaultKinds, 286 const common::LanguageFeatureControl &languageFeatures, 287 parser::AllCookedSources &allCookedSources) 288 : defaultKinds_{defaultKinds}, languageFeatures_{languageFeatures}, 289 allCookedSources_{allCookedSources}, 290 intrinsics_{evaluate::IntrinsicProcTable::Configure(defaultKinds_)}, 291 globalScope_{*this}, intrinsicModulesScope_{globalScope_.MakeScope( 292 Scope::Kind::IntrinsicModules, nullptr)}, 293 foldingContext_{ 294 parser::ContextualMessages{&messages_}, defaultKinds_, intrinsics_} {} 295 296 SemanticsContext::~SemanticsContext() {} 297 298 int SemanticsContext::GetDefaultKind(TypeCategory category) const { 299 return defaultKinds_.GetDefaultKind(category); 300 } 301 302 const DeclTypeSpec &SemanticsContext::MakeNumericType( 303 TypeCategory category, int kind) { 304 if (kind == 0) { 305 kind = GetDefaultKind(category); 306 } 307 return globalScope_.MakeNumericType(category, KindExpr{kind}); 308 } 309 const DeclTypeSpec &SemanticsContext::MakeLogicalType(int kind) { 310 if (kind == 0) { 311 kind = GetDefaultKind(TypeCategory::Logical); 312 } 313 return globalScope_.MakeLogicalType(KindExpr{kind}); 314 } 315 316 bool SemanticsContext::AnyFatalError() const { 317 return !messages_.empty() && 318 (warningsAreErrors_ || messages_.AnyFatalError()); 319 } 320 bool SemanticsContext::HasError(const Symbol &symbol) { 321 return errorSymbols_.count(symbol) > 0; 322 } 323 bool SemanticsContext::HasError(const Symbol *symbol) { 324 return !symbol || HasError(*symbol); 325 } 326 bool SemanticsContext::HasError(const parser::Name &name) { 327 return HasError(name.symbol); 328 } 329 void SemanticsContext::SetError(const Symbol &symbol, bool value) { 330 if (value) { 331 CheckError(symbol); 332 errorSymbols_.emplace(symbol); 333 } 334 } 335 void SemanticsContext::CheckError(const Symbol &symbol) { 336 if (!AnyFatalError()) { 337 std::string buf; 338 llvm::raw_string_ostream ss{buf}; 339 ss << symbol; 340 common::die( 341 "No error was reported but setting error on: %s", ss.str().c_str()); 342 } 343 } 344 345 const Scope &SemanticsContext::FindScope(parser::CharBlock source) const { 346 return const_cast<SemanticsContext *>(this)->FindScope(source); 347 } 348 349 Scope &SemanticsContext::FindScope(parser::CharBlock source) { 350 if (auto *scope{globalScope_.FindScope(source)}) { 351 return *scope; 352 } else { 353 common::die( 354 "SemanticsContext::FindScope(): invalid source location for '%s'", 355 source.ToString().c_str()); 356 } 357 } 358 359 bool SemanticsContext::IsInModuleFile(parser::CharBlock source) const { 360 for (const Scope *scope{&FindScope(source)}; !scope->IsGlobal(); 361 scope = &scope->parent()) { 362 if (scope->IsModuleFile()) { 363 return true; 364 } 365 } 366 return false; 367 } 368 369 void SemanticsContext::PopConstruct() { 370 CHECK(!constructStack_.empty()); 371 constructStack_.pop_back(); 372 } 373 374 void SemanticsContext::CheckIndexVarRedefine(const parser::CharBlock &location, 375 const Symbol &variable, parser::MessageFixedText &&message) { 376 const Symbol &symbol{ResolveAssociations(variable)}; 377 auto it{activeIndexVars_.find(symbol)}; 378 if (it != activeIndexVars_.end()) { 379 std::string kind{EnumToString(it->second.kind)}; 380 Say(location, std::move(message), kind, symbol.name()) 381 .Attach(it->second.location, "Enclosing %s construct"_en_US, kind); 382 } 383 } 384 385 void SemanticsContext::WarnIndexVarRedefine( 386 const parser::CharBlock &location, const Symbol &variable) { 387 CheckIndexVarRedefine(location, variable, 388 "Possible redefinition of %s variable '%s'"_warn_en_US); 389 } 390 391 void SemanticsContext::CheckIndexVarRedefine( 392 const parser::CharBlock &location, const Symbol &variable) { 393 CheckIndexVarRedefine( 394 location, variable, "Cannot redefine %s variable '%s'"_err_en_US); 395 } 396 397 void SemanticsContext::CheckIndexVarRedefine(const parser::Variable &variable) { 398 if (const Symbol * entity{GetLastName(variable).symbol}) { 399 CheckIndexVarRedefine(variable.GetSource(), *entity); 400 } 401 } 402 403 void SemanticsContext::CheckIndexVarRedefine(const parser::Name &name) { 404 if (const Symbol * entity{name.symbol}) { 405 CheckIndexVarRedefine(name.source, *entity); 406 } 407 } 408 409 void SemanticsContext::ActivateIndexVar( 410 const parser::Name &name, IndexVarKind kind) { 411 CheckIndexVarRedefine(name); 412 if (const Symbol * indexVar{name.symbol}) { 413 activeIndexVars_.emplace( 414 ResolveAssociations(*indexVar), IndexVarInfo{name.source, kind}); 415 } 416 } 417 418 void SemanticsContext::DeactivateIndexVar(const parser::Name &name) { 419 if (Symbol * indexVar{name.symbol}) { 420 auto it{activeIndexVars_.find(ResolveAssociations(*indexVar))}; 421 if (it != activeIndexVars_.end() && it->second.location == name.source) { 422 activeIndexVars_.erase(it); 423 } 424 } 425 } 426 427 SymbolVector SemanticsContext::GetIndexVars(IndexVarKind kind) { 428 SymbolVector result; 429 for (const auto &[symbol, info] : activeIndexVars_) { 430 if (info.kind == kind) { 431 result.push_back(symbol); 432 } 433 } 434 return result; 435 } 436 437 SourceName SemanticsContext::SaveTempName(std::string &&name) { 438 return {*tempNames_.emplace(std::move(name)).first}; 439 } 440 441 SourceName SemanticsContext::GetTempName(const Scope &scope) { 442 for (const auto &str : tempNames_) { 443 if (IsTempName(str)) { 444 SourceName name{str}; 445 if (scope.find(name) == scope.end()) { 446 return name; 447 } 448 } 449 } 450 return SaveTempName(".F18."s + std::to_string(tempNames_.size())); 451 } 452 453 bool SemanticsContext::IsTempName(const std::string &name) { 454 return name.size() > 5 && name.substr(0, 5) == ".F18."; 455 } 456 457 Scope *SemanticsContext::GetBuiltinModule(const char *name) { 458 return ModFileReader{*this}.Read(SourceName{name, std::strlen(name)}, 459 true /*intrinsic*/, nullptr, true /*silence errors*/); 460 } 461 462 void SemanticsContext::UseFortranBuiltinsModule() { 463 if (builtinsScope_ == nullptr) { 464 builtinsScope_ = GetBuiltinModule("__fortran_builtins"); 465 if (builtinsScope_) { 466 intrinsics_.SupplyBuiltins(*builtinsScope_); 467 } 468 } 469 } 470 471 parser::Program &SemanticsContext::SaveParseTree(parser::Program &&tree) { 472 return modFileParseTrees_.emplace_back(std::move(tree)); 473 } 474 475 bool Semantics::Perform() { 476 // Implicitly USE the __Fortran_builtins module so that special types 477 // (e.g., __builtin_team_type) are available to semantics, esp. for 478 // intrinsic checking. 479 if (!program_.v.empty()) { 480 const auto *frontModule{std::get_if<common::Indirection<parser::Module>>( 481 &program_.v.front().u)}; 482 if (frontModule && 483 std::get<parser::Statement<parser::ModuleStmt>>(frontModule->value().t) 484 .statement.v.source == "__fortran_builtins") { 485 // Don't try to read the builtins module when we're actually building it. 486 } else { 487 context_.UseFortranBuiltinsModule(); 488 } 489 } 490 return ValidateLabels(context_, program_) && 491 parser::CanonicalizeDo(program_) && // force line break 492 CanonicalizeAcc(context_.messages(), program_) && 493 CanonicalizeOmp(context_.messages(), program_) && 494 PerformStatementSemantics(context_, program_) && 495 ModFileWriter{context_}.WriteAll(); 496 } 497 498 void Semantics::EmitMessages(llvm::raw_ostream &os) const { 499 context_.messages().Emit(os, context_.allCookedSources()); 500 } 501 502 void Semantics::DumpSymbols(llvm::raw_ostream &os) { 503 DoDumpSymbols(os, context_.globalScope()); 504 } 505 506 void Semantics::DumpSymbolsSources(llvm::raw_ostream &os) const { 507 NameToSymbolMap symbols; 508 GetSymbolNames(context_.globalScope(), symbols); 509 const parser::AllCookedSources &allCooked{context_.allCookedSources()}; 510 for (const auto &pair : symbols) { 511 const Symbol &symbol{pair.second}; 512 if (auto sourceInfo{allCooked.GetSourcePositionRange(symbol.name())}) { 513 os << symbol.name().ToString() << ": " << sourceInfo->first.file.path() 514 << ", " << sourceInfo->first.line << ", " << sourceInfo->first.column 515 << "-" << sourceInfo->second.column << "\n"; 516 } else if (symbol.has<semantics::UseDetails>()) { 517 os << symbol.name().ToString() << ": " 518 << symbol.GetUltimate().owner().symbol()->name().ToString() << "\n"; 519 } 520 } 521 } 522 523 void DoDumpSymbols(llvm::raw_ostream &os, const Scope &scope, int indent) { 524 PutIndent(os, indent); 525 os << Scope::EnumToString(scope.kind()) << " scope:"; 526 if (const auto *symbol{scope.symbol()}) { 527 os << ' ' << symbol->name(); 528 } 529 if (scope.alignment().has_value()) { 530 os << " size=" << scope.size() << " alignment=" << *scope.alignment(); 531 } 532 if (scope.derivedTypeSpec()) { 533 os << " instantiation of " << *scope.derivedTypeSpec(); 534 } 535 os << '\n'; 536 ++indent; 537 for (const auto &pair : scope) { 538 const auto &symbol{*pair.second}; 539 PutIndent(os, indent); 540 os << symbol << '\n'; 541 if (const auto *details{symbol.detailsIf<GenericDetails>()}) { 542 if (const auto &type{details->derivedType()}) { 543 PutIndent(os, indent); 544 os << *type << '\n'; 545 } 546 } 547 } 548 if (!scope.equivalenceSets().empty()) { 549 PutIndent(os, indent); 550 os << "Equivalence Sets:"; 551 for (const auto &set : scope.equivalenceSets()) { 552 os << ' '; 553 char sep = '('; 554 for (const auto &object : set) { 555 os << sep << object.AsFortran(); 556 sep = ','; 557 } 558 os << ')'; 559 } 560 os << '\n'; 561 } 562 if (!scope.crayPointers().empty()) { 563 PutIndent(os, indent); 564 os << "Cray Pointers:"; 565 for (const auto &[pointee, pointer] : scope.crayPointers()) { 566 os << " (" << pointer->name() << ',' << pointee << ')'; 567 } 568 } 569 for (const auto &pair : scope.commonBlocks()) { 570 const auto &symbol{*pair.second}; 571 PutIndent(os, indent); 572 os << symbol << '\n'; 573 } 574 for (const auto &child : scope.children()) { 575 DoDumpSymbols(os, child, indent); 576 } 577 --indent; 578 } 579 580 static void PutIndent(llvm::raw_ostream &os, int indent) { 581 for (int i = 0; i < indent; ++i) { 582 os << " "; 583 } 584 } 585 586 void SemanticsContext::MapCommonBlockAndCheckConflicts(const Symbol &common) { 587 if (!commonBlockMap_) { 588 commonBlockMap_ = std::make_unique<CommonBlockMap>(); 589 } 590 commonBlockMap_->MapCommonBlockAndCheckConflicts(*this, common); 591 } 592 593 CommonBlockList SemanticsContext::GetCommonBlocks() const { 594 if (commonBlockMap_) { 595 return commonBlockMap_->GetCommonBlocks(); 596 } 597 return {}; 598 } 599 600 } // namespace Fortran::semantics 601