https://gcc.gnu.org/bugzilla/show_bug.cgi?id=84867
Bug ID: 84867 Summary: Wrong code generated, except at -O0, with inappropriate Warning: iteration 1 invokes undefined behavior [-Waggressive-loop-optimizations] Product: gcc Version: 6.4.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: fortran Assignee: unassigned at gcc dot gnu.org Reporter: jiri.pitt...@jh-inst.cas.cz Target Milestone: --- Created attachment 43656 --> https://gcc.gnu.org/bugzilla/attachment.cgi?id=43656&action=edit source codes demonstrating the problem Many old F77 codes in my research field use a 'hack' to dynamically allocate a memory by a malloc() called from C, while referring to the allocated memory by an index with respect to an array declared in a common block. When used in a way when a loop of constant length gets unrolled, the compiler produced Warning: iteration 1 invokes undefined behavior [-Waggressive-loop-optimizations] at any optimization level higher than -O0 and generated wrong assembly code with a single instruction movsd %xmm3, 7999976(%r15,%rax,8) rather than 6 instructions from the completely unrolled loops movsd %xmm3, (%rbx,%rax,8) movsd %xmm3, 8(%rbx,%rax,8) movsd %xmm3, 16(%rbx,%rax,8) movsd %xmm6, 7999976(%rbx,%rax,8) movsd %xmm6, 7999984(%rbx,%rax,8) movsd %xmm6, 7999992(%rbx,%rax,8) Interestingly, after declaring common/formal/work(2) both the problem and the warning disappears, although formally the dimensions of the array work() are also exceeded. Although formally viewed this way of doing dynamic allocation is a dirty hack exceeding declared array dimensions (and crossing even to a different virtual memory section by a huge array index), it is widespread in old codes and should not be broken. I have observed the same behavior with a wide range of gfortran versions from 4.9.3 to 7.3.0 (installed under gentoo linux).