This is the mail archive of the gcc-bugs@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

[Bug fortran/30003] New: Expressions with side effects in array references


(This bug was discovered during a discussion on the mailinglist starting here:
http://gcc.gnu.org/ml/fortran/2006-11/msg00636.html) 

This short program

erik:~$ cat foo.f90
program foo

    implicit none
    integer :: a(5), b(3)

    b = [ 1, 2, 3 ]
    a(1:bar(3)) = b

contains
    integer function bar(n)
        integer, intent(in) :: n
        print *, 'Hello!'
        bar = n
    end function bar
end program foo

should, when compiled and run, call bar() once, and, hence, print 'hello!'
once.  But when compiled without -fbounds-check, it doesn't print anything:

erik:~$ gfortran foo.f90 
erik:~$ a.out

This is because gfortran will actually never evaluate the expression of the
size of the LHS; it will just assume the LHS has the same size as the RHS. 
That would be OK if the expression of the size didn't have side effects, but in
a case like this, it gives wrong results.

If we compile with -fbounds-check, it gets really strange:

erik:~$ gfortran foo.f90 -fbounds-check
erik:~$ a.out
 Hello!
 Hello!
 Hello!
 Hello!
 Hello!
 Hello!
 Hello!
 Hello!
 Hello!
 Hello!
 Hello!
 Hello!
 Hello!


Here, bar() is called 13 times!  This is because bar() is called separately for
every check that the value of bar() is within bounds etc. Again, this would be
OK (albeit a bit inefficient) if bar() had no side effects, but with side
effects it gives wrong results.  

Also consider the case where bar():s result value depends on e.g. a SAVEd
variable, so that it returns different values every time it's called (even if
called with the same argument).  That could give _really_ wierd behaviour.


-- 
           Summary: Expressions with side effects in array references
           Product: gcc
           Version: 4.3.0
            Status: UNCONFIRMED
          Keywords: wrong-code
          Severity: normal
          Priority: P3
         Component: fortran
        AssignedTo: eedelman at gcc dot gnu dot org
        ReportedBy: eedelman at gcc dot gnu dot org


http://gcc.gnu.org/bugzilla/show_bug.cgi?id=30003


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]