Index: flang/lib/Lower/PFTBuilder.cpp =================================================================== --- flang/lib/Lower/PFTBuilder.cpp +++ flang/lib/Lower/PFTBuilder.cpp @@ -161,7 +161,8 @@ } else if constexpr (lower::pft::isConstruct || lower::pft::isDirective) { if constexpr (lower::pft::isDeclConstruct) - return; + if (pftParentStack.back().getIf()) + return; exitConstructOrDirective(); } } @@ -317,10 +318,12 @@ pftParentStack.emplace_back(eval); constructAndDirectiveStack.emplace_back(&eval); if constexpr (lower::pft::isDeclConstruct) { - popEvaluationList(); - pftParentStack.pop_back(); - constructAndDirectiveStack.pop_back(); - popEvaluationList(); + if (pftParentStack.back().getIf()) { + popEvaluationList(); + pftParentStack.pop_back(); + constructAndDirectiveStack.pop_back(); + popEvaluationList(); + } } return true; } Index: flang/test/Lower/pre-fir-tree06.f90 =================================================================== --- flang/test/Lower/pre-fir-tree06.f90 +++ flang/test/Lower/pre-fir-tree06.f90 @@ -10,3 +10,30 @@ end ! CHECK: End ModuleLike +! CHECK: Program main +program main + real :: y + ! CHECK-NEXT: OpenMPDeclarativeConstruct + !$omp threadprivate(y) +end +! CHECK: End Program main + +! CHECK: Subroutine sub1 +subroutine sub1() + real, save :: p + ! CHECK-NEXT: OpenMPDeclarativeConstruct + !$omp threadprivate(p) +end +! CHECK: End Subroutine sub1 + +! CHECK: Subroutine sub2 +subroutine sub2() + real, save :: q + ! CHECK-NEXT: OpenMPDeclarativeConstruct + !$omp threadprivate(q) +contains + subroutine sub() + end +end +! CHECK: End Subroutine sub2 +