diff --git a/flang/lib/Lower/Bridge.cpp b/flang/lib/Lower/Bridge.cpp --- a/flang/lib/Lower/Bridge.cpp +++ b/flang/lib/Lower/Bridge.cpp @@ -2179,6 +2179,19 @@ unsigned typeGuardIdx = 0; std::size_t defaultAttrPos = std::numeric_limits::max(); bool hasLocalScope = false; + llvm::SmallVector typeCaseScopes; + + const auto &typeCaseList = + std::get>( + selectTypeConstruct.t); + for (const auto &typeCase : typeCaseList) { + const auto &stmt = + std::get>( + typeCase.t); + const Fortran::semantics::Scope &scope = + bridge.getSemanticsContext().FindScope(stmt.source); + typeCaseScopes.push_back(&scope); + } for (Fortran::lower::pft::Evaluation &eval : getEval().getNestedEvaluations()) { @@ -2275,13 +2288,11 @@ "TypeGuard attribute missing"); mlir::Attribute typeGuardAttr = attrList[typeGuardIdx]; mlir::Block *typeGuardBlock = blockList[typeGuardIdx]; - const Fortran::semantics::Scope &guardScope = - bridge.getSemanticsContext().FindScope(eval.position); mlir::OpBuilder::InsertPoint crtInsPt = builder->saveInsertionPoint(); builder->setInsertionPointToStart(typeGuardBlock); auto addAssocEntitySymbol = [&](fir::ExtendedValue exv) { - for (auto &symbol : guardScope.GetSymbols()) { + for (auto &symbol : typeCaseScopes[typeGuardIdx]->GetSymbols()) { if (symbol->GetUltimate() .detailsIf()) { addSymbol(symbol, exv); diff --git a/flang/test/Lower/select-type.f90 b/flang/test/Lower/select-type.f90 --- a/flang/test/Lower/select-type.f90 +++ b/flang/test/Lower/select-type.f90 @@ -756,6 +756,23 @@ ! CHECK: ^bb6: ! CHECK: ^bb7: + subroutine select_type14(a, b) + class(p1) :: a, b + + select type(a) + type is (p2) + select type (b) + type is (p2) + print*,a%c,b%C + end select + class default + print*,a%a + end select + end subroutine + + ! Just makes sure the example can be lowered. + ! CHECK-LABEL: func.func @_QMselect_type_lower_testPselect_type14 + end module program test_select_type