flang icon indicating copy to clipboard operation
flang copied to clipboard

F03/F08: Flang frees memory which is used later and cause undefined behavior.

Open Narutoworld opened this issue 3 years ago • 2 comments

The following code expose this bug.

module m
  implicit none

  type t
     integer, allocatable, dimension(:) :: r
  end type t

contains

  function tt(a,b)
    implicit none
    type(t), allocatable, dimension(:) :: tt
    type(t), intent(in), dimension(:) :: a,b
    allocate(tt, source = [a,b])
  end function tt

  function ts(arg)
    implicit none
    type(t), allocatable, dimension(:) :: ts
    integer, intent(in) :: arg(:)
    allocate(ts(1))
    allocate(ts(1)%r, source = arg)
    return
  end function ts

end module m

program p
  use m
  implicit none
  type(t), dimension(2) :: c, d
  c=tt(ts([99,199,1999]),ts([42,142]))
  d=tt(ts([1,2,3]),ts([4,5]))
  if (any (c(1)%r .ne. [99,199,1999])) STOP 1
  if (any (d(1)%r .ne. [1,2,3])) STOP 2
  if (any (c(2)%r .ne. [42,142])) STOP 3
  if (any (d(2)%r .ne. [4,5])) STOP 4
end program p

Narutoworld avatar Sep 21 '22 14:09 Narutoworld

With gfortran-9.4.0, result is

gfortran p.f90
./a.out
echo $?
0

However with flang master branch, result is

flang p.f90
./a.out
    1
echo $?
1

Narutoworld avatar Sep 21 '22 15:09 Narutoworld

A bit investigation shows that Flang frees relevant memory pointing to c(1)%r, before executing if (any (c(1)%r .ne. [99,199,1999])) STOP 1

Narutoworld avatar Sep 21 '22 15:09 Narutoworld

Our investigation shows that flang1 seems to be skipping a necessary deep copy of the allocatable array fields in the derived type elements while constructing the result array from the source array(s). @pawosm-arm @kiranchandramohan @shivaramaarao Have you guys seen this before?

bryanpkc avatar Sep 26 '22 22:09 bryanpkc