Wrong code generation with pointer arithmetic

Bug #1864494 reported by Thomas Bernard
10
This bug affects 2 people
Affects Status Importance Assigned to Milestone
GNU Arm Embedded Toolchain
Confirmed
High
Vasee Vinayagamoorthy

Bug Description

When compiling the following code (also in attached file) with gcc-9 2019-q4 and -O2 wrong code is generated:

typedef unsigned int uint32_t;
uint32_t* init(uint32_t *ptr1, uint32_t *ptr2)
{
  ptr2 = (uint32_t*)(((uint32_t)ptr2)& (~((uint32_t)3)));
  *(--ptr2) = 0x77777777;
  if((reinterpret_cast<uint32_t>(ptr2) &0x7) !=0 )
  {
    *(--ptr2) = ~0x77777777;
  }
  return ptr2;
}

Command line:

gcc-arm-none-eabi-9-2019-q4-major/bin/arm-none-eabi-g++ -O2 -mcpu=cortex-m3 -S wrong_optimization.cpp

The assembler generated is:

LFB0:
 @ args = 0, pretend = 0, frame = 0
 @ frame_needed = 0, uses_anonymous_args = 0
 @ link register save eliminated.
 mov r3, #2004318071
 bic r1, r1, #3
 str r3, [r1, #-4]
 lsls r3, r1, #29
 sub r0, r1, #4
 bmi .L1
 mov r3, #-2004318072
 sub r0, r1, #8
 str r3, [r1, #-8]
.L1:
 bx lr

The lsls r3, r1, #29 instruction doesn't use the intended address.

The gcc-7 compiler outputs correct code.

gcc-arm-none-eabi-7-2017-q4-major/bin/arm-none-eabi-g++ -O2 -mcpu=cortex-m3 -S wrong_optimization.cpp

This produces:

.LFB0:
 @ args = 0, pretend = 0, frame = 0
 @ frame_needed = 0, uses_anonymous_args = 0
 @ link register save eliminated.
 mov r3, #2004318071
 bic r1, r1, #3
 subs r0, r1, #4
 str r3, [r1, #-4]
 lsls r3, r0, #29
 bpl .L1
 mov r3, #-2004318072
 sub r0, r1, #8
 str r3, [r1, #-8]
.L1:
 bx lr

Which is correct.

Tags: 2019q4
Revision history for this message
Thomas Bernard (teajay-fr) wrote :
tags: added: 2019q4
Joey Ye (jinyun-ye)
Changed in gcc-arm-embedded:
status: New → Confirmed
importance: Undecided → High
assignee: nobody → Vasee Vinayagamoorthy (vvinayag)
Revision history for this message
Ras (rasdpm) wrote :

The same behaviour is also present in the GCC 9 2020q2 release.

Was that report deemed not to be a bug and should have been closed?

Or did it do unaddressed? In this case, the process for reporting and handling bugs would need to be reviewed.

Revision history for this message
Dennis Wong (binencoder) wrote :

I've had similar problems with pointer arithmetic, maybe you can try adding compiler options -fno-tree-vrp and -fno-tree-dominator-opts to avoid misoptimization.

To post a comment you must log in.
This report contains Public information  
Everyone can see this information.

Other bug subscribers

Remote bug watches

Bug watches keep track of this bug in other bug trackers.