https://gcc.gnu.org/bugzilla/show_bug.cgi?id=112459

            Bug ID: 112459
           Summary: gfortran -w option causes derived-type finalization at
                    creation time
           Product: gcc
           Version: 13.2.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: fortran
          Assignee: unassigned at gcc dot gnu.org
          Reporter: bardeau at iram dot fr
  Target Milestone: ---

Hi everyone,

with gfortran version 13.2.0, the -w compilation switch modifies the code
behavior at execution time. This was not the case with e.g. gfortran 12.1.0.

~> gfortran -v
Using built-in specs.
COLLECT_GCC=gfortran
COLLECT_LTO_WRAPPER=/home/bardeau/Softs/gcc-13.2.0/libexec/gcc/x86_64-pc-linux-gnu/13.2.0/lto-wrapper
Target: x86_64-pc-linux-gnu
Configured with: ../srcdir/configure --with-gmp=/home/bardeau/Softs/gcc-deps
--prefix=/home/bardeau/Softs/gcc-13.2.0 --enable-languages=c,c++,fortran
--disable-multilib
Thread model: posix
Supported LTO compression algorithms: zlib
gcc version 13.2.0 (GCC)

Code example:

module mymod
  type mysubtype
    integer(kind=4), allocatable :: a(:)
  end type mysubtype
  type :: mytype
    integer :: i
    type(mysubtype) :: sub
  contains
    final :: mytype_final
  end type mytype
contains
  subroutine mysubtype_final(sub)
    type(mysubtype), intent(inout) :: sub
    print *,'MYSUBTYPE>FINAL'
    if (allocated(sub%a)) deallocate(sub%a)
  end subroutine mysubtype_final
  subroutine mytype_final(typ)
    type(mytype), intent(inout) :: typ
    print *,"MYTYPE>FINAL"
    call mysubtype_final(typ%sub)
  end subroutine mytype_final
end module mymod
!
program myprog
  use mymod
  type(mytype), pointer :: c
  print *,"Before allocation"
  allocate(c)
  print *,"After allocation"
end program myprog

Compilation and execution:

~> gfortran -w test1.f90 -o test1 && ./test1
 Before allocation
 MYTYPE>FINAL
 MYSUBTYPE>FINAL
 After allocation

The problem is that the FINAL procedure (mytype_final) is invoked at the time
the c variable is allocated, which is unexpected. Plus, this behavior is
random. If the "sub" component is removed from "mytype", mytype_final is not
invoked anymore. I also have a much more complex example where the program
crashes because the evaluation "allocated(sub%a)" is incorrect and leads to
deallocation of the unallocated "sub%a". All these behaviors are correlated to
the presence of the -w option.

In order to be complete, I must say that the -w option is not described in
https://gcc.gnu.org/onlinedocs/gcc-13.2.0/gfortran/Error-and-Warning-Options.html
but it is suggested in -fallow-argument-mismatch (documented here:
https://gcc.gnu.org/onlinedocs/gcc-13.2.0/gfortran/Fortran-Dialect-Options.html
). In practice it can be used for example with:

subroutine test
  call foo()
  call foo(1)
end subroutine test

~> gfortran -c -fallow-argument-mismatch -w test2.f90

which shows no warning thanks to -w.

Reply via email to