Bug 22278

Summary: gcc -O2 discards cast to volatile
Product: gcc Reporter: olivier.baudron
Component: tree-optimizationAssignee: Richard Henderson <rth>
Status: RESOLVED FIXED    
Severity: normal CC: gcc-bugs, gcc2eran, hugh, james, pawel_sikora
Priority: P2 Keywords: documentation
Version: 4.1.0   
Target Milestone: 4.0.2   
Host: i686-pc-linux-gnu Target:
Build: Known to work:
Known to fail: Last reconfirmed: 2005-07-17 16:36:37

Description olivier.baudron 2005-07-02 16:43:23 UTC
In the following testcase, a read memory access should be made.
However gcc -O2 optimizes away the code inside the test function.

------------------- test.c --------------------
void test (char *addr) {
        *((volatile char *) addr);
}
-----------------------------------------------

$ gcc -Wall -O2 -S test.c

------------------- test.s --------------------
test.s:
        .file   "test.c"
        .text
        .p2align 4,,15
.globl test
        .type   test, @function
test:
        pushl   %ebp
        movl    %esp, %ebp
        popl    %ebp
        ret
        .size   test, .-test
        .ident  "GCC: (GNU) 4.1.0 20050702 (experimental)"
        .section        .note.GNU-stack,"",@progbits
-----------------------------------------------
Comment 1 Andrew Pinski 2005-07-02 16:48:35 UTC
See PR 21568 and http://gcc.gnu.org/ml/gcc/2005-05/msg00085.html.

This is allowed by the C and C++ standards.

*** This bug has been marked as a duplicate of 21568 ***
Comment 2 olivier.baudron 2005-07-02 16:59:31 UTC
I am not sure this is the same problem.
Besides, the following code is *not* optimized away with -O2:

void test (volatile char *addr) {
        *addr;
}
Comment 3 Andrew Pinski 2005-07-02 17:03:52 UTC
Did you read the message which I referenced?  it is still not a bug if you read the message.
Comment 4 Falk Hueffner 2005-07-02 17:33:54 UTC
I see a difference here in that gcc doesn't know whether the referenced
object is declared to be volatile, it isn't visible as in PR 21568.
IMHO we actually have a bug here; I don't see anything in the standard which
allows omitting the access here.
Comment 5 Andrew Pinski 2005-07-02 17:42:46 UTC
Since the orginal pointer is not violatile the cast will not change any thing since the compiler can  
deduce it is not violatile.
From C99, 5.1.2.3 P3:
In the abstract machine, all expressions are evaluated as specified by the semantics. An actual 
implementation need not evaluate part of an expression if it can deduce that its value is not used and 
that no needed side effects are produced (including anycaused by calling a function or accessing a 
volatile object). 

and since violatile applies the type which is being pointed to and not to the pointer, the compiler can 
deduce it is not needed.
Casting away the violatile in a pointer changes the behavior (just like const).
Comment 6 Falk Hueffner 2005-07-02 17:53:29 UTC
(In reply to comment #5)
> Since the orginal pointer is not violatile the cast will not change any thing
since the compiler can  
> deduce it is not violatile.

It could deduce that if it was invalid to form a pointer to non-volatile
that points to a volatile object. However, I can't see any point in the standard
that disallows this. So how can gcc deduce the pointed-to object is not volatile?
Comment 7 Falk Hueffner 2005-07-02 20:38:19 UTC
According to Joseph Myers, the question is whether this counts as "access" to
a volatile object, which is implementation defined (6.7.3#6). However,
extend.texi doesn't answer this, so I'll reopen it as a documentation problem.
We could then either document it does not constitute an access, or change
the behavior and state that it does.
Comment 8 gcc2eran 2005-07-02 22:07:46 UTC
Prior versions of gcc did "respect" casts to pointer-to-volatile and did not
optimize away the access. I've seen a lot of code that relies on that, and which
would thus be broken by gcc 4.x (in a subtle and hard-to-debug way). One recent
example is an elusive bug in Fedora Core 4's X.org package which bit many users
(https://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=161242).

I can't imagine a programmer casting into a pointer to volatile without really
meaning it, so if the behavior is not defined by the standard then both
compatibility and the principle of least astonishment seem to suggest reverting
to the old behavior.
Comment 9 Gabriel Dos Reis 2005-07-02 22:08:35 UTC
Subject: Re:  gcc -O2 discards cast to volatile

"pinskia at gcc dot gnu dot org" <gcc-bugzilla@gcc.gnu.org> writes:

| See PR 21568 and http://gcc.gnu.org/ml/gcc/2005-05/msg00085.html.

Both those issues about completely *different* from the issue
submitted in this PR.  In the above cases, the accessed object actually
is NOT volatile.  This is not the same here.

In this PR, the only thing the function sees is that its parameter
is not declared pointer to volatile char, but just pointer to char.
That is NO basis for the compiler to assume that the cast performed
inside the body is invalid assumption.  No. Never.  
Consequently, it must assume that the pointed-to object might be
effectively volatile and consequently generate corresponding code.

There is a difference between cv-qualified object and a pointer to
cv-qualified object.  In the former cases, you do know for sure how
the object behaves, in the latter you don't.  Consequently you must
make conervative assumptions.

|            What    |Removed                     |Added
| ----------------------------------------------------------------------------
|              Status|UNCONFIRMED                 |RESOLVED
|          Resolution|                            |DUPLICATE

Andrew --

  Once again, refrain from closing an issue when you do not fully
understand the issue at hand.

The PR should be reopen as wrong-code generation.

-- Gaby
Comment 10 Gabriel Dos Reis 2005-07-02 22:10:24 UTC
Subject: Re:  gcc -O2 discards cast to volatile

"pinskia at gcc dot gnu dot org" <gcc-bugzilla@gcc.gnu.org> writes:


| Did you read the message which I referenced?

Not just because people disagrees with your view means that they did
not read what you wrote.  

|  it is still not a bug if you read the message.

I read the message and it bears no ressemblance to the specific case
at hand here.  Please stop closing PR based on half-digested material.

-- Gaby
Comment 11 Gabriel Dos Reis 2005-07-02 22:10:55 UTC
Subject: Re:  gcc -O2 discards cast to volatile

"falk at debian dot org" <gcc-bugzilla@gcc.gnu.org> writes:

| I see a difference here in that gcc doesn't know whether the referenced
| object is declared to be volatile, it isn't visible as in PR 21568.

Fully agreed.

| IMHO we actually have a bug here; I don't see anything in the standard which
| allows omitting the access here.

again agreed.

-- Gaby
Comment 12 Gabriel Dos Reis 2005-07-02 22:11:56 UTC
Subject: Re:  gcc -O2 discards cast to volatile

"pinskia at gcc dot gnu dot org" <gcc-bugzilla@gcc.gnu.org> writes:

| Since the orginal pointer is not violatile

How do you know that?  Just looking at function *parameter*?  Sorry,
that is no reason.

-- Gaby
Comment 13 Gabriel Dos Reis 2005-07-02 22:12:34 UTC
Subject: Re:  gcc -O2 discards cast to volatile

"falk at debian dot org" <gcc-bugzilla@gcc.gnu.org> writes:

| According to Joseph Myers, the question is whether this counts as "access" to
| a volatile object, which is implementation defined (6.7.3#6). However,
| extend.texi doesn't answer this, so I'll reopen it as a documentation problem.
| We could then either document it does not constitute an access, or change
| the behavior and state that it does.
| 
| 
| -- 
|            What    |Removed                     |Added
| ----------------------------------------------------------------------------
|              Status|RESOLVED                    |UNCONFIRMED
|            Keywords|                            |documentation

It is also wrong-code.

-- Gaby
Comment 14 Falk Hueffner 2005-07-02 22:19:29 UTC
(In reply to comment #8)

> I can't imagine a programmer casting into a pointer to volatile without really
> meaning it, so if the behavior is not defined by the standard then both
> compatibility and the principle of least astonishment seem to suggest reverting
> to the old behavior.

I agree in principle. It might just turn out to be too hard to guarantee, in
which case we might as well document that.
Comment 15 Andrew Pinski 2005-07-02 22:20:06 UTC
(In reply to comment #13)
> 
> It is also wrong-code.

This is the opposite view of what JSM said on IRC.  Take it up with him if you believe otherwise.
Basically this is all implemention defined and since we did not document before, we have a chance to 
define it to what we want.
Comment 16 Gabriel Dos Reis 2005-07-02 22:20:39 UTC
Subject: Re:  gcc -O2 discards cast to volatile

"gcc2eran at tromer dot org" <gcc-bugzilla@gcc.gnu.org> writes:


| Prior versions of gcc did "respect" casts to pointer-to-volatile and did not
| optimize away the access. I've seen a lot of code that relies on that, and which
| would thus be broken by gcc 4.x (in a subtle and hard-to-debug way). One recent
| example is an elusive bug in Fedora Core 4's X.org package which bit many users
| (https://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=161242).
| 
| I can't imagine a programmer casting into a pointer to volatile without really
| meaning it, so if the behavior is not defined by the standard then both
| compatibility and the principle of least astonishment seem to suggest reverting
| to the old behavior.


We must be careful in distinguishing between the following two
situations:

  (1)  volatile int foo = 0;
  
      *(volatile int*) (int*) (&foo);

  (2) int bar = 0;
      *(volatile int*) (&bar);

The former is well-formed and GCC should be careful.  In the specific
case at hand, the first cast may be passed to the function that is
subject of this PR, and GCC has no way of knowing what is going behind
the scene.  Consequently, it must make the conservative assumption.

The latter is just not well-founded based on the C standard.  It is a
QoI whether GCC should honor it or not.  I have no strong opinion
there, except saying that it is questionable.

-- Gaby
Comment 17 Gabriel Dos Reis 2005-07-02 22:39:42 UTC
Subject: Re:  gcc -O2 discards cast to volatile

"pinskia at gcc dot gnu dot org" <gcc-bugzilla@gcc.gnu.org> writes:

| (In reply to comment #13)
| > 
| > It is also wrong-code.
| 
| This is the opposite view of what JSM said on IRC.

Sorry, I do not follow IRC, and it would be unfortunate that PRs get
closed based on claims we do not have logs for so that users and
people can look at them and scrutinize.  

Furthermore, the fundamental issue is whether this

   *(volatile int*) (int*) (&foo);

(or equivalent) where foo has been defined volatile int  should be
treated differently from 

   *(volatile int*) (&foo);

 or 

   foo;


For all useful purposes, it helps remembering that GCC is not an
academic exercise in C standard reading.

|  Take it up with him if you believe otherwise.
| Basically this is all implemention defined and since we did not
| document before, we have a chance to  define it to what we want.

and it is hard to believe we (GCC developers aiming at useful compiler,
as opposed to students doing academic exercise) will define it to be
either contradictory or the most useless as possible.

-- Gaby
Comment 18 Andrew Pinski 2005-07-02 22:49:23 UTC
> For all useful purposes, it helps remembering that GCC is not an
> academic exercise in C standard reading.
Ok, then all of your comments about extensions to C++ should be thrown out the window since I know 
you are against extensions.  If someone is going to program in C or C++, they should know they are 
going to get into trouble when programming and get something different than what they expect and 
should go read the standard to double check if they got it right or the compiler is correct.  
Comment 19 gcc2eran 2005-07-02 23:30:05 UTC
(In reply to comment #17)
> Furthermore, the fundamental issue is whether this
> 
>    *(volatile int*) (int*) (&foo);
> 
> (or equivalent) where foo has been defined volatile int  should be
> treated differently from 
> 
>    *(volatile int*) (&foo);
> 
>  or 
> 
>    foo;

How about this?

    int foo; 
    *(volatile int*) (&foo);

In other words, why should the compiler bother at all with the qualifiers of
what the pointer "really" points to? It seems simplest and most natural to
decree that any dereference of a pointer-to-volatile (regardless of its origin)
is to be treated as volatile and thus never optimized away. In other words,
"volatile" should treated as a property of the type of the pointer being
dereferenced, not of the actual object being pointed to.

By analogy, if I write

    long bar = 42;
    x = *(char*)bar;

then the compiler won't optimize this (into a SEGV?) just because it can easily
tell that bar didn't "really" originate from a char*. Rather, it will take my
word that (char*)bar should be treated just like any char*. Sure, it might
optimize this subject to the usual semantics of char* -- but in case of
volatiles, these semantics (should) forbid certain optimizations.
Comment 20 Falk Hueffner 2005-07-02 23:45:51 UTC
(In reply to comment #19)

> How about this?
> 
>     int foo; 
>     *(volatile int*) (&foo);
> 
> In other words, why should the compiler bother at all with the qualifiers of
> what the pointer "really" points to?

Because the standard says so. As Nathan Sidwell explains in the thread
linked above, it would be both pretty difficult to define the language
extension you want semantically clean, and to implement it in gcc. So 
nobody tried yet. (Giving a warning would probably be less difficult to
implement, unfortunately nobody tried either.)
Comment 21 Gabriel Dos Reis 2005-07-02 23:54:31 UTC
Subject: Re:  gcc -O2 discards cast to volatile

"pinskia at gcc dot gnu dot org" <gcc-bugzilla@gcc.gnu.org> writes:

| > For all useful purposes, it helps remembering that GCC is not an
| > academic exercise in C standard reading.
| Ok, then all of your comments about extensions to C++ should be
| > thrown out the window 

No, you just chose to selectively misread statements.  That is
unfortunate, but we have to live with it.

| since I know you are against extensions.

You know nothing about me, so lease stick to GCC.

| If someone is going to program in C or C++, they should know they are 
| going to get into trouble when programming and get something
| different than what they expect and should go read the standard to
| double check if they got it right or the compiler is correct.   

yes, but that is orthogonal to the issue at hand.

-- Gaby
Comment 22 Gabriel Dos Reis 2005-07-03 00:03:38 UTC
Subject: Re:  gcc -O2 discards cast to volatile

"gcc2eran at tromer dot org" <gcc-bugzilla@gcc.gnu.org> writes:

| ------- Additional Comments From gcc2eran at tromer dot org  2005-07-02 23:30 -------
| (In reply to comment #17)
| > Furthermore, the fundamental issue is whether this
| > 
| >    *(volatile int*) (int*) (&foo);
| > 
| > (or equivalent) where foo has been defined volatile int  should be
| > treated differently from 
| > 
| >    *(volatile int*) (&foo);
| > 
| >  or 
| > 
| >    foo;
| 
| How about this?
| 
|     int foo; 
|     *(volatile int*) (&foo);

It was included in my previous message.

| In other words, why should the compiler bother at all with the qualifiers of
| what the pointer "really" points to?

Because the language definition says that the compiler should preserve
a semantics and the compiler better bothers.

| It seems simplest and most natural to
| decree that any dereference of a pointer-to-volatile (regardless of
| its origin) is to be treated as volatile and thus never optimized
| away. In other words, "volatile" should treated as a property of the
| type of the pointer being dereferenced, not of the actual object
| being pointed to. 

but that is a fundamental departure from the language semantics.
Replace "volatile" with "const" -- both are qualifiers -- and observe
the disaster that would ensue.

The "volatile" cv-qualified is interesting in the sense that it is
fuzzily defined, but there are identities that the compiler must
preserve. 

-- Gaby
Comment 23 gcc2eran 2005-07-03 01:19:45 UTC
(In reply to comment #22)
> |     int foo; 
> |     *(volatile int*) (&foo);
> 
> It was included in my previous message.

Then it's still eluding me, since your foo (the "object"?) was volatile.


> | In other words, why should the compiler bother at all with the qualifiers of
> | what the pointer "really" points to?
> 
> Because the language definition says that the compiler should preserve
> a semantics and the compiler better bothers.

Of course, but please forgive my ignorance -- where does does the standard 
prescribe these semantics? The N869 draft (I don't have the standard; is N869
best fall-back?) says this:

"[6.7.3/6] An object that has volatile-qualified type may be modified in ways
unknown to the lementation or have other unknown side effects. Therefore any
expression referring to such an object shall be evaluated strictly according to
the rules of the abstract machine, as described in 5.1.2.3. [...]"

All other references to the semantics volatile likewise talk about objects. So,
what is an object?

"[3.15/1] object: region of data storage in the execution environment, the
contents of which can represent values"
"[3.15/2] NOTE When referenced, an object may be interpreted as having a
particular type; see 6.3.2.1."

What indeed is the type of an object?

"[6.3.2.1/1] [...] When an object is said to have a particular type, the type is
specified by the lvalue used to designate the object. [...]"

And also, later on:

"[6.5.3.2/4] The unary * operator denotes indirection. If the operand [...]
points to an object, the result is an lvalue designating the
object. If the operand has type ‘‘pointer to type’’, the result has type
‘‘type’’. [...]"

And just to be sure about whether "volatile" is part of the type thus specified
by the lvalue:

"[6.2.5/26] [...] The qualified or unqualified versions of a type are distinct
types [...]."

So the way I read it, the object designated by *(volatile int*)(anything) has a
 volatile-qualified type and should thus be evaluated strictly according to the
rules of the abstract machine.


> but that is a fundamental departure from the language semantics.
> Replace "volatile" with "const" -- both are qualifiers -- and observe
> the disaster that would ensue.

I must be showing my ignorance again, but what disaster would that be?



BTW, according to your interpretation, what is the standard-compliant behavior
of the following?

  void quux(int *bar) {
    *bar = 42;
  }

  volatile int foo;
  quux((int*)&foo);

I'm asking because as of 4.0.0, the assignment is optimized away by -O3.
Comment 24 jsm-csl@polyomino.org.uk 2005-07-03 01:27:24 UTC
Subject: Re:  gcc -O2 discards cast to volatile

On Sun, 3 Jul 2005, gcc2eran at tromer dot org wrote:

> Of course, but please forgive my ignorance -- where does does the standard 
> prescribe these semantics? The N869 draft (I don't have the standard; is N869
> best fall-back?) says this:

Get the standard, not ancient drafts.  As I pointed out on the gcc list a 
while back, N1124 is the result of merging C99 with TC1 and TC2 and is 
freely available on the WG14 site.

Comment 25 Gabriel Dos Reis 2005-07-03 01:42:06 UTC
Subject: Re:  gcc -O2 discards cast to volatile

"gcc2eran at tromer dot org" <gcc-bugzilla@gcc.gnu.org> writes:

| > but that is a fundamental departure from the language semantics.
| > Replace "volatile" with "const" -- both are qualifiers -- and observe
| > the disaster that would ensue.
| 
| I must be showing my ignorance again, but what disaster would that be?

If when the compiler sees "const T* p", it assumes that *p is
effectively const, then it would miscompile

   int foo(int* p, const int* q) {
       int r = *q;
       *p = r * r;
       return *q;
   }

If the compiler assumed that *q is effectively const, therefore cannot
have its value changed through *p, then the following assertion will fail

    int i = 4;
    assert(foo(&i, &i) == 16);

because the compiler could just return the cached value "r". 

There is more a pointer than just its type. 

| BTW, according to your interpretation, what is the standard-compliant behavior
| of the following?
| 
|   void quux(int *bar) {
|     *bar = 42;
|   }
| 
|   volatile int foo;
|   quux((int*)&foo);

       [#5] If an attempt is made to modify an object defined  with
       a  const-qualified  type  through use of an lvalue with non-
       const-qualified type, the  behavior  is  undefined.   If  an
       attempt  is  made  to  refer  to  an  object  defined with a
       volatile-qualified type through use of an lvalue  with  non-
       volatile-qualified type, the behavior is undefined.113)

The footnote says

       113This applies to those objects that behave as if they were
          defined with qualified types,  even  if  they  are  never
          actually  defined  as  objects in the program (such as an
          object at a memory-mapped input/output address).


-- Gaby
Comment 26 Gabriel Dos Reis 2005-07-03 01:43:42 UTC
Subject: Re:  gcc -O2 discards cast to volatile

"gcc2eran at tromer dot org" <gcc-bugzilla@gcc.gnu.org> writes:

| (In reply to comment #22)
| > |     int foo; 
| > |     *(volatile int*) (&foo);
| > 
| > It was included in my previous message.
| 
| Then it's still eluding me, since your foo (the "object"?) was volatile.

It was my object "bar".

-- Gaby
Comment 27 gcc2eran 2005-07-03 01:46:57 UTC
(In reply to comment #24)

Thanks! 
None of the quotes and references in comment 23 changed in N1124.
Comment 28 D. Hugh Redelmeier 2005-07-03 01:53:55 UTC
[ see https://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=162274 ]

I feel that he gcc documentation promises that there will be an access.  The
documentation can change, but it is a contract between the implementer and the C
programmer.  Breaking a contract is not very nice.  Especially when it can cause
quiet subtle breakage of a program.

"info gcc" node "Volatiles" with title "6.1 When is a Volatile Object Accessed?"
clearly says:

<<Less obvious expressions are where something which looks like an access
is used in a void context.  An example would be,

     volatile int *src = SOMEVALUE;
     *src;

 With C, such expressions are rvalues, and as rvalues cause a read of
the object, GCC interprets this as a read of the volatile being pointed
to.>>

Now it turns out that gcc4 does *not* optimize away the access in:
void test(char *addr)
{
        volatile char *t = addr;
        (void) (*t);
}

Surely the motivating example in this bugzilla entry should be covered by the
same logic.
Comment 29 gcc2eran 2005-07-03 02:30:08 UTC
(In reply to comment #25)
> If when the compiler sees "const T* p", it assumes that *p is
> effectively const, then it would miscompile
> 
>    int foo(int* p, const int* q) {
>        int r = *q;
>        *p = r * r;
>        return *q;
>    }
>
> If the compiler assumed that *q is effectively const, therefore cannot
> have its value changed through *p, then the following assertion will fail
> 
>     int i = 4;
>     assert(foo(&i, &i) == 16);
> 
> because the compiler could just return the cached value "r". 

We need to distinguish between the semantics that that must be followed, and
optimizations that preserve these semantics. The way I understand it,
semantics-wise "const" is not a promise, it's only a requirement: it tells the
compiler that it can't change the object directly, that's all. Meanwhile, the
optimizer tries to do various optimizations that preserve the semantics, for
example by noting that variables don't change their values; but in your example
it can't make that assumption without aliasing analysis (which will fail), since
by itself the const-qualified argument guarantees nothing.

So the standard says the semantics are dumb: they considers just the type of the
dereferenced pointer and acts accordingly (forbid direct changes of consts,
apply strict abstrat machine for volatiles). But subject to those semantics, the
optimizer can be as smart as it wants. There's no contradiction here.


>        [#5] If an attempt is made to modify an object defined  with
>        a  const-qualified  type  through use of an lvalue with non-
>        const-qualified type, the  behavior  is  undefined.   If  an
>        attempt  is  made  to  refer  to  an  object  defined with a
>        volatile-qualified type through use of an lvalue  with  non-
>        volatile-qualified type, the behavior is undefined.113)

OK. Then the volatile-stripping direction can be handled arbitrarily.


(In reply to comment #26)
> It was my object "bar".

OK. I was looking at comment 17.
Comment 30 Gabriel Dos Reis 2005-07-03 02:54:54 UTC
Subject: Re:  gcc -O2 discards cast to volatile

"gcc2eran at tromer dot org" <gcc-bugzilla@gcc.gnu.org> writes:

| >        [#5] If an attempt is made to modify an object defined  with
| >        a  const-qualified  type  through use of an lvalue with non-
| >        const-qualified type, the  behavior  is  undefined.   If  an
| >        attempt  is  made  to  refer  to  an  object  defined with a
| >        volatile-qualified type through use of an lvalue  with  non-
| >        volatile-qualified type, the behavior is undefined.113)
| 
| OK. Then the volatile-stripping direction can be handled arbitrarily.

I do not understand that comment.

-- Gaby
Comment 31 gcc2eran 2005-07-03 04:14:21 UTC
(In reply to comment #30)
> | OK. Then the volatile-stripping direction can be handled arbitrarily.
> 
> I do not understand that comment.

I meant that we were mostly concerned about what the standard says about the
effect of casting (say) int* into volatile int*, but the other directly is
simply undefined. 

Still, consider the following variant:

  void quux(int *bar) {
    *(volatile int*)bar = 42;
  }

  volatile int foo;
  quux((int*)&foo);

This time there is no "attempt [...] to refer to an object defined with a
volatile-qualified type through use of an lvalue with non-volatile-qualified
type". So why does gcc 4.0.0 -O3 still optimize away the assignment? And how
would you fix that with an approach that construes the standard to require
following the type of the "real" object?

Could the standard intend something so convoluted, when the interpretation in
comment 23 makes things perfectly sensible, well-defined and (in principle) easy
to implement?
Comment 32 Gabriel Dos Reis 2005-07-03 04:43:27 UTC
Subject: Re:  gcc -O2 discards cast to volatile

"gcc2eran at tromer dot org" <gcc-bugzilla@gcc.gnu.org> writes:

| (In reply to comment #30)
| > | OK. Then the volatile-stripping direction can be handled arbitrarily.
| > 
| > I do not understand that comment.
| 
| I meant that we were mostly concerned about what the standard says about the
| effect of casting (say) int* into volatile int*, but the other directly is
| simply undefined. 

That is what I do not understand.  Could you point me to the relevant
passage of the C standard?

| Still, consider the following variant:
| 
|   void quux(int *bar) {
|     *(volatile int*)bar = 42;
|   }
| 
|   volatile int foo;
|   quux((int*)&foo);
| 
| This time there is no "attempt [...] to refer to an object defined with a
| volatile-qualified type through use of an lvalue with non-volatile-qualified
| type".


Really?  What does quux() does to the object defined through foo then?

| So why does gcc 4.0.0 -O3 still optimize away the assignment? And how
| would you fix that with an approach that construes the standard to require
| following the type of the "real" object?
| 
| Could the standard intend something so convoluted, when the interpretation in
| comment 23 makes things perfectly sensible, well-defined and (in principle) easy
| to implement?

My understanding is that you have gotten everything backwards.

-- Gaby
Comment 33 gcc2eran 2005-07-03 05:09:16 UTC
(In reply to comment #32)
> | I meant that we were mostly concerned about what the standard says about the
> | effect of casting (say) int* into volatile int*, but the other directly is
> | simply undefined. 
> 
> That is what I do not understand.  Could you point me to the relevant
> passage of the C standard?

(my quote above should read "the other *direction* is simply undefined")

Uhm? It's just the passage you quoted earlier:
"If an attempt is made to refer to an object defined with a volatile-qualified
type through use of an lvalue with non-volatile-qualified type, the behavior is
undefined".


> 
> |   void quux(int *bar) {
> |     *(volatile int*)bar = 42;
> |   }
> | 
> |   volatile int foo;
> |   quux((int*)&foo);
> | 
> | This time there is no "attempt [...] to refer to an object defined with a
> | volatile-qualified type through use of an lvalue with non-volatile-qualified
> | type".
> 
> Really?  What does quux() does to the object defined through foo then?

It refers to it through an lvalue whose type is "volatile int", which *is*
volatile-qualified.


> My understanding is that you have gotten everything backwards.

In what sense?
Comment 34 Gabriel Dos Reis 2005-07-03 05:11:14 UTC
Subject: Re:  gcc -O2 discards cast to volatile

"gdr at integrable-solutions dot net" <gcc-bugzilla@gcc.gnu.org> writes:

| | Still, consider the following variant:
| | 
| |   void quux(int *bar) {
| |     *(volatile int*)bar = 42;
| |   }
| | 
| |   volatile int foo;
| |   quux((int*)&foo);
| | 
| | This time there is no "attempt [...] to refer to an object defined with a
| | volatile-qualified type through use of an lvalue with non-volatile-qualified
| | type".
| 
| 
| Really?

that comment is wrong, sorry.  You're right.  (time for me to go to bed).
Yes, this is a bug in GCC.

-- Gaby
Comment 35 Gabriel Dos Reis 2005-07-03 05:18:16 UTC
Subject: Re:  gcc -O2 discards cast to volatile

"gcc2eran at tromer dot org" <gcc-bugzilla@gcc.gnu.org> writes:

| ------- Additional Comments From gcc2eran at tromer dot org  2005-07-03 05:09 -------
| (In reply to comment #32)
| > | I meant that we were mostly concerned about what the standard says about the
| > | effect of casting (say) int* into volatile int*, but the other directly is
| > | simply undefined. 
| > 
| > That is what I do not understand.  Could you point me to the relevant
| > passage of the C standard?
| 
| (my quote above should read "the other *direction* is simply undefined")

"the other direction" was very ambiguous.

[...]

| > Really?  What does quux() does to the object defined through foo then?
| 
| It refers to it through an lvalue whose type is "volatile int", which *is*
| volatile-qualified.

yes, you're right.

-- Gaby
Comment 36 D. Hugh Redelmeier 2005-07-03 05:40:10 UTC
Simple rule about const and volatile qualifiers (not restrict): the program can
manipulate pointer values with and without their qualifiers.  But when the
program accesses an object that is a  volatile object (i.e. defined, created, or
fundamentally volatile), it must be via a volatile lvalue.  And when the program
accesses an object that was created const (defined, created, or fundamentally
const), then it must not be modifying it.

Optimizers must not presume more.  Well, there is a tricky rule about aliasing
in N1124 section 6.5 (see footnote 74 on page 68), based on the unqualified
types.  But we're only talking about qualifiers.  And another about multiple
modifications between sequence points -- again, not relevant here.

So I think that gcc4 is wrong for this case: the access should not be optimized out.
Comment 37 gcc2eran 2005-07-03 06:59:34 UTC
(In reply to comment #34)

OK, that was just a demonstration of of the problem you pointed out in comments
9 and 12 and example (a) of comment 16. In this case, your analysis ("be
conservative") and my reading of the standard (comment 23) lead to identical
conclusions.

This leaves example (b) of comment 16, where the "real object" is non-volatile.
Here we seem to still disagree: you said it's a QoI and "not well-founded on the
C standard", hence currently not a bug and "fixing" it would be a gcc extension.
I argued, in comment 23, that this too is a bug, since the standard says that
any access to an lvalue with volatile-qualified type must be left untouched. But
this case seems to fall under PR 21568, which I believe should be reopened. For
convenience I copied the relevant parts of comment 23 to that PR.
Comment 38 Paul Schlie 2005-07-03 07:09:20 UTC
(In reply to comment #35)
> Subject: Re:  gcc -O2 discards cast to volatile

I apologize for interjecting, but wanted to verify my perception the
conclusions reached; are they essentially?:

- although an object referenced through a qualified lvalue which differs
  from that object's declaration may result in an undefined behavior (as
  an implementation may specifically allocate objects based upon their
  respective qualification, therefore may result in an unanticipated
  behavior if referenced as being dissimilarly qualified).
  
- that object should be effectively be treated as specified by that
  qualified lvalue unless the compiler knows factually that it's
  correspondingly implied side effects will not affect the program's
  otherwise specified behavior.

(where lvalue in this context is any object's reference,
which may refer to either a source, or destination value.)

Therefore:

  int i;
  const int ci:
  volatile int vi;

  *(int*)&ci = 0; // should treat ci as int, although may result in
                  // unexpected behavior as const may be read-only.

  int* foo(const int * ci){
    return (int*)ci;
  }
  *(foo(ci)) = 0; // as above.

  *(int)&vi = 0;   // should treat as non-volatile, although may
                         // may result in unexpected behavior if special
                         // volatile things happen when a volatile allocated
                         // object is physically addressed for example.

  *(volatile int*)&i = 0; // should treat as volatile, although may
                          // result in unexpected behavior if true
                          // volatile objects need to be declared as
                          // such to be specially allocated to satisfy
                          // an implementation's defined behavior.
Comment 39 Gabriel Dos Reis 2005-07-03 07:27:03 UTC
Subject: Re:  gcc -O2 discards cast to volatile

"schlie at comcast dot net" <gcc-bugzilla@gcc.gnu.org> writes:

| (In reply to comment #35)
| > Subject: Re:  gcc -O2 discards cast to volatile
| 
| I apologize for interjecting, but wanted to verify my perception the
| conclusions reached; are they essentially?:
| 
| - although an object referenced through a qualified lvalue which differs
|   from that object's declaration may result in an undefined behavior (as
|   an implementation may specifically allocate objects based upon their
|   respective qualification, therefore may result in an unanticipated
|   behavior if referenced as being dissimilarly qualified).
|   
| - that object should be effectively be treated as specified by that
|   qualified lvalue unless the compiler knows factually that it's
|   correspondingly implied side effects will not affect the program's
|   otherwise specified behavior.
| 
| (where lvalue in this context is any object's reference,
| which may refer to either a source, or destination value.)
| 
| Therefore:
| 
|   int i;
|   const int ci:
|   volatile int vi;
| 
|   *(int*)&ci = 0; // should treat ci as int, although may result in
|                   // unexpected behavior as const may be read-only.

This is undefined behaviour and on plateforms where GCC put const
object in read-only sections, you're in serious troubles.  Other
compilers may do more "interesting" things, or less.

|   int* foo(const int * ci){
|     return (int*)ci;
|   }
|   *(foo(ci)) = 0; // as above.

Yes, again undefined behaviour.

|   *(int)&vi = 0;   // should treat as non-volatile, although may
|                          // may result in unexpected behavior if special
|                          // volatile things happen when a volatile allocated
|                          // object is physically addressed for example.

undefined behaviour -- assuming you meant *(int*)&vi -- quotes from
the standard already provided. 

|   *(volatile int*)&i = 0; // should treat as volatile, although may
|                           // result in unexpected behavior if true
|                           // volatile objects need to be declared as
|                           // such to be specially allocated to satisfy
|                           // an implementation's defined behavior.

This is unclear, reported in past and considered bugs is user codes as
far as GCC is concerned.  gcc2eran thinks this should be accepted.
The issue is further confused by the fact that C has a rather
interesting formulation of its object model.  

-- Gaby
Comment 40 Paul Schlie 2005-07-03 07:54:32 UTC
(In reply to comment #39)
> Subject: Re:  gcc -O2 discards cast to volatile

So unfortunately, again the question which comes to mind is what
should happen when a program specifies an undefined behavior?

Personally it seems most generally useful to warn that the behavior
is undefined, but treat the objects as specified, as would be expected.
(as the alternative would neither be expected nor well defined)
Comment 41 Nathanael C. Nerode 2005-07-15 05:50:25 UTC
OK, so in X.org, the key area where this is hit is the definition of     
MMIO_IN8 in compiler.h.  For alpha, sparc, and powerpc, inline volatile     
ASM is used instead (much better in some ways).     
     
The vanishing line is:       
(void) minb(hwp->IOBase + VGA_IN_STAT_1_OFFSET);       
This expands in preprocessing to:       
(void) MMIO_IN8(hwp->MMIOBase, (hwp->MMIOOffset + (hwp->IOBase +      
VGA_IN_STAT_1_OFFSET)))       
which further expands in preprocessing in compiler.h (except for     
sparc, alpha and powerpc) to:     
(void) *(volatile CARD8 *)( (CARD8*)(hwp->MMIOBase) + hwp->MMIOOffset +     
hwp->IOBase + VGA_IN_STAT_1_OFFSET)     
     
The key expansion is this one:     
#  define MMIO_IN8(base, offset) \     
        *(volatile CARD8 *)(((CARD8*)(base)) + (offset))     
     
This obviously doesn't work and perhaps it shouldn't work.  But what is a     
good alternative implementation?  Essentially, we're trying to force a read  
of an arbitrary memory address.  If the "underlying object" has  
to be volatile, how do we make it volatile?  Can we simply create a new  
"underlying object" by throwing in a temporary pointer variable?  Is something  
like the following sufficient to force an access?  
  
static inline unsigned char myMmioIn8(volatile void* base,  
                                      const unsigned long offset)  
{  
  volatile CARD8 * tmp = (CARD8*)base + offset;  
  return *tmp;  
}  
#  define MMIO_IN8(base, offset) myMmioIn8(base, offset)    
  
If that's not sufficient, I don't see any way to accomplish the required  
behavior under gcc 4.0 (without massive rewriting of the X.org code), so I 
hope it is.  
  
Comment 42 Gabriel Dos Reis 2005-07-15 07:51:52 UTC
Subject: Re:  gcc -O2 discards cast to volatile

"neroden at gcc dot gnu dot org" <gcc-bugzilla@gcc.gnu.org> writes:


[...]

| of an arbitrary memory address.  If the "underlying object" has  
| to be volatile, how do we make it volatile?  Can we simply create a new  
| "underlying object" by throwing in a temporary pointer variable?  Is something  
| like the following sufficient to force an access?  
|   
| static inline unsigned char myMmioIn8(volatile void* base,  
|                                       const unsigned long offset)  
| {  
|   volatile CARD8 * tmp = (CARD8*)base + offset;  
|   return *tmp;  
| }  

If is fragile.  If the compiler does more aggressive inline (which I
hope 4.0 doesn't, but 4.x may at some point) and discover that the
chains of conversion started with something it thinks really not
volatile, then it would behave the same way as with the macro.

| #  define MMIO_IN8(base, offset) myMmioIn8(base, offset)    
|   
| If that's not sufficient, I don't see any way to accomplish the required  
| behavior under gcc 4.0 (without massive rewriting of the X.org code), so I 
| hope it is.  

I've come to believe that GCC's current choice is needlessly
unhelpful.  I think  it is much more reasonable to have GCC leave its
optimizer fingers out of the access through volatile lvalue, whether
the object behind is really defined volatile of not -- GCC cannot
know and the programmer cannot if is the "object behind" is actually
never defined, but is mapped to a memory.  Unfortunately, I don't know
the extent of the GCC code that needs to be fixed so I don't know
whether it is fixable in 4.0.  

-- Gaby
Comment 43 D. Hugh Redelmeier 2005-07-16 16:18:04 UTC
Here is some C Lawyering from Henry Spencer.  I asked him to look at and comment
on this bug.  With his permission, I'm quoting his response here.

There is little room for compiler writers to maneuver here, unless they
have announced their intentions in advance in their documentation. 
Reading C99 carefully:

6.5.3.2:  applying `*' to a pointer of type `T *' which points to an
object yields an lvalue of type `T' designating that object.  So the
lvalue in the assignment has a volatile-qualified type. 

6.3.2.1:  when an object is said to have a particular type, the type is
specified by the lvalue used to designate the object.  So the lvalue
having a volatile-qualified type *means* that the object it designates has
a volatile-qualified type; "has type X" and "is designated by an lvalue of
type X" are synonymous (!).

6.7.3:  any expression referring to an object of volatile-qualified
type must be evaluated strictly by the rules of the abstract machine,
although precisely what constitutes an "access" to the object is
implementation-defined.  (Note, "implementation-defined" behavior is
required to be well-defined and *documented*.)  So if the reference in
question is an "access", it must occur where the abstract machine says
it should.

5.1.2.3:  the abstract machine evaluates all expressions as specified by
semantics and all side effects must occur, side effects including
"accessing a volatile object"; implementations are allowed to skip part
of expression evaluation only if they can deduce that no needed side
effects (notably "accessing a volatile object") are therefore skipped. 
So if the reference is an "access", it must occur, period.

I see no useful wiggle room in the difference between "access" and
"accessing", or the difference between "volatile object" and "object of
volatile-qualified type".  These appear to me to be minor accidents of
inconsistent terminology, not useful to a sane implementer.

6.7.3 says that to refer to an object "defined with" volatile-qualified
type "through use of an lvalue" with non-volatile-qualified type yields
undefined behavior.  However, the reference here uses a volatile-qualified
lvalue, so this is not relevant.  A pointer value is not an lvalue; there
is no lvalue present until the `*' operator is applied. 

Surprising though it might seem, I see no express or implied permission to
distinguish based on whether the object in question was *defined* with a
volatile-qualified type.  There are places in the standard where how an
object is defined is significant, e.g. the rules for `const' and the part
of 6.7.3 noted in the previous paragraph, but none of them is part of the
chain of reasoning above.

The only loophole is the definition of "access".  If GCC wishes to claim
standard conformance, GCC is required to document its definition.  I'm not
aware of any mention of this in the GCC documentation, although I haven't
dug hard for it. 

I see no room for a reasonable definition of "access" which retains some
useful meaning for `volatile' and doesn't cover the reference in question. 
(I agree that you can contrive a definition which contains special-case
wording to cover this case, but not that it's reasonable to do so.)

If GCC (a) wants to be C99-conforming, and (b) wants to provide useful
semantics for `volatile', this is a bug.
Comment 44 Gabriel Dos Reis 2005-07-16 16:35:50 UTC
Subject: Re:  gcc -O2 discards cast to volatile

"hugh at mimosa dot com" <gcc-bugzilla@gcc.gnu.org> writes:

[...]

| If GCC (a) wants to be C99-conforming, and (b) wants to provide useful
| semantics for `volatile', this is a bug.

Based on discussions via private mails, I've become even more
convinced that we should just honor the volatile access as written by
the programmer.  Furthermore, this should be clearly documented.
Patches are welcome!

-- Gaby
Comment 45 D. Hugh Redelmeier 2005-07-17 08:04:32 UTC
There is a thread on the gcc at gcc.gnu.org mailing list discussing this.  A
possible fix to GCC4.x has been posted in that thread:
  http://gcc.gnu.org/ml/gcc/2005-07/msg00699.html
Comment 46 GCC Commits 2005-07-19 20:20:51 UTC
Subject: Bug 22278

CVSROOT:	/cvs/gcc
Module name:	gcc
Changes by:	rth@gcc.gnu.org	2005-07-19 20:20:42

Modified files:
	gcc            : ChangeLog gimplify.c tree-ssa.c 

Log message:
	PR tree-opt/22278
	* gimplify.c (gimplify_expr): Use main variant type for the temp
	destination for a discarded volatile read.
	* tree-ssa.c (tree_ssa_useless_type_conversion_1): Don't elide
	casts between non-void types that change volatility.

Patches:
http://gcc.gnu.org/cgi-bin/cvsweb.cgi/gcc/gcc/ChangeLog.diff?cvsroot=gcc&r1=2.9479&r2=2.9480
http://gcc.gnu.org/cgi-bin/cvsweb.cgi/gcc/gcc/gimplify.c.diff?cvsroot=gcc&r1=2.140&r2=2.141
http://gcc.gnu.org/cgi-bin/cvsweb.cgi/gcc/gcc/tree-ssa.c.diff?cvsroot=gcc&r1=2.105&r2=2.106

Comment 47 GCC Commits 2005-07-20 00:07:22 UTC
Subject: Bug 22278

CVSROOT:	/cvs/gcc
Module name:	gcc
Branch: 	gcc-4_0-branch
Changes by:	rth@gcc.gnu.org	2005-07-20 00:06:50

Modified files:
	gcc            : ChangeLog gimplify.c tree-ssa.c 

Log message:
	PR tree-opt/22278
	* gimplify.c (gimplify_expr): Use main variant type for the temp
	destination for a discarded volatile read.
	* tree-ssa.c (tree_ssa_useless_type_conversion_1): Don't elide
	casts between non-void types that change volatility.

Patches:
http://gcc.gnu.org/cgi-bin/cvsweb.cgi/gcc/gcc/ChangeLog.diff?cvsroot=gcc&only_with_tag=gcc-4_0-branch&r1=2.7592.2.320&r2=2.7592.2.321
http://gcc.gnu.org/cgi-bin/cvsweb.cgi/gcc/gcc/gimplify.c.diff?cvsroot=gcc&only_with_tag=gcc-4_0-branch&r1=2.113.2.7&r2=2.113.2.8
http://gcc.gnu.org/cgi-bin/cvsweb.cgi/gcc/gcc/tree-ssa.c.diff?cvsroot=gcc&only_with_tag=gcc-4_0-branch&r1=2.78.2.2&r2=2.78.2.3

Comment 48 Richard Henderson 2005-07-20 00:11:01 UTC
Fixed.
Comment 49 GCC Commits 2005-08-11 23:56:36 UTC
Subject: Bug 22278

CVSROOT:	/cvs/gcc
Module name:	gcc
Branch: 	apple-local-200502-branch
Changes by:	mrs@gcc.gnu.org	2005-08-11 23:56:06

Modified files:
	gcc            : gimplify.c tree-ssa.c ChangeLog 

Log message:
	PR tree-opt/22278
	* gimplify.c (gimplify_expr): Use main variant type for the temp
	destination for a discarded volatile read.
	* tree-ssa.c (tree_ssa_useless_type_conversion_1): Don't elide
	casts between non-void types that change volatility.
	Radar 4098854

Patches:
http://gcc.gnu.org/cgi-bin/cvsweb.cgi/gcc/gcc/gimplify.c.diff?cvsroot=gcc&only_with_tag=apple-local-200502-branch&r1=2.111.2.5&r2=2.111.2.6
http://gcc.gnu.org/cgi-bin/cvsweb.cgi/gcc/gcc/tree-ssa.c.diff?cvsroot=gcc&only_with_tag=apple-local-200502-branch&r1=2.76.4.2&r2=2.76.4.3
http://gcc.gnu.org/cgi-bin/cvsweb.cgi/gcc/gcc/ChangeLog.diff?cvsroot=gcc&only_with_tag=apple-local-200502-branch&r1=2.7489.2.18&r2=2.7489.2.19