473,289 Members | 1,791 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,289 software developers and data experts.

Another ANSI C question about 'volatile'

Here's another question related to 'volatile'. Consider
the following:

int x;

void
foo(){
int y;

y = (volatile int) x;

... further computations involving y (but no assignments to y) ...

}

My belief is that the standard allows optimizing away the variable 'y'
and re-using the value in 'x' (that is, re-loading 'x' to get the
value again). In particular, I'm thinking of the passage that says
type qualifiers are ignored except for expressions that are lvalue's,
and the casted value of 'x' isn't an lvalue.

Questions:

1. Does the language of the standard allow this optimizing away of 'y'
or not (with reasoning, please)?

2. Assuming it does, what's a better way to get the effect intended
here, namely, to cause the value of 'x' to be put in a local so
that it's guaranteed that a local copy is made and 'x' is not
referenced further?
Thanks again.
Nov 14 '05 #1
8 2595
Tim Rentsch <tx*@alumnus.caltech.edu> writes:
Here's another question related to 'volatile'. Consider
the following:

int x;

void
foo(){
int y;

y = (volatile int) x;

... further computations involving y (but no assignments to y) ...

}

My belief is that the standard allows optimizing away the variable 'y'
and re-using the value in 'x' (that is, re-loading 'x' to get the
value again). In particular, I'm thinking of the passage that says
type qualifiers are ignored except for expressions that are lvalue's,
and the casted value of 'x' isn't an lvalue.

Questions:

1. Does the language of the standard allow this optimizing away of 'y'
or not (with reasoning, please)?

2. Assuming it does, what's a better way to get the effect intended
here, namely, to cause the value of 'x' to be put in a local so
that it's guaranteed that a local copy is made and 'x' is not
referenced further?


I think you're looking for:

volatile int y = x;

Why do you want to do this?

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #2
Keith Thompson <ks***@mib.org> writes:
Tim Rentsch <tx*@alumnus.caltech.edu> writes:

int x;

void
foo(){
int y;

y = (volatile int) x;

... further computations involving y (but no assignments to y) ...

}

[snipped]


I think you're looking for:

volatile int y = x;

Why do you want to do this?


Sorry I wasn't more clear on this. The idea is to force the compiler
to use an actual local variable to hold the value of 'x', but then
allow that variable to be optimized freely. Kind of a "locally
treat 'x' as volatile even though it isn't declared that way."
Does that make sense? I realize it isn't really an answer to
the "Why" question, but hopefully it clarifies things enough
so that a means can be suggested.

thanks again.

Nov 14 '05 #3
>> Tim Rentsch <tx*@alumnus.caltech.edu> writes:
int x;
void
foo(){
int y;

y = (volatile int) x;

... further computations involving y (but no assignments to y) ...

}
Keith Thompson <ks***@mib.org> writes:
I think you're looking for:
volatile int y = x;
Why do you want to do this?

In article <news:kf*************@alumnus.caltech.edu>
Tim Rentsch <tx*@alumnus.caltech.edu> wrote:Sorry I wasn't more clear on this. The idea is to force the compiler
to use an actual local variable to hold the value of 'x', but then
allow that variable to be optimized freely. Kind of a "locally
treat 'x' as volatile even though it isn't declared that way."
Does that make sense?


Scarily, yes :-)

This is not what I would consider "good style" but will achieve
the effect:

int x;
...
void f(void) {
int y = *(volatile int *)&x;
... use y as needed ...
}

Equivalently, and perhaps slightly better (but still not "great")
style:

void f(void) {
/*
* NOTE TO MAINTAINERS: references through *xp read or write
* x as if x were declared volatile, even though it is not.
* This can be used to trick the compiler into doing operations
* with partial ordering constraints without having total
* ordering constraints.
*/
volatile int *xp = &x;
int y = *xp;
... use y and/or *xp as needed ...
}

Fundamentally, the problem is that things like Partial Store Order
or Relaxed Memory Order multiprocessing models do not fit well with
the C language -- C is too high-level for these. Depending on
one's compiler, though, it may be possible to insert memory barriers
and convince the compiler not to move memory operations across
those barriers, while permitting all optimizations that do not
cross such barriers. (With gcc, use "__asm__ volatile" and include
"memory" in the set of "clobbered" operands, for instance.)

This is all *way* outside the realm of Standard C, which does not
support multiprocessing at all, and has quite limited support for
interruptions (such as signals) in a single-processing model.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 14 '05 #4
Chris Torek <no****@torek.net> writes:
[lots of earlier stuff omitted]
This is not what I would consider "good style" but will achieve
the effect:

int x;
...
void f(void) {
int y = *(volatile int *)&x;
... use y as needed ...
}

Equivalently, and perhaps slightly better (but still not "great")
style:

void f(void) {
/*
* NOTE TO MAINTAINERS: references through *xp read or write
* x as if x were declared volatile, even though it is not.
* This can be used to trick the compiler into doing operations
* with partial ordering constraints without having total
* ordering constraints.
*/
volatile int *xp = &x;
int y = *xp;
... use y and/or *xp as needed ...
}


Thank you Chris for these helpful replies.

I'd thought of the 'y = *(volatile int *)&x;' before, but I concluded
it had the same problem as 'y = (volatile int)x;' -- because the
subexpression '(volatile int *)&x' isn't an lvalue (by which I mean,
can't be on the left hand side of an assignment operator), the
'volatile' type qualifier is discarded. Or do I misunderstand
what the standard means by 'lvalue'?

The other solution, with 'volatile int *xp = &x;', seems to
work just fine. That's great, I hadn't thought of that.

Incidentally, what about this idea:

int * volatile xp = &x, y = *xp;

Seems like that also would force actual evaluation into a
'y' temporary, even imagining a compiler smart enough to
figure out that 'y' is getting the value in 'x'. Yes?

Fundamentally, the problem is that things like Partial Store Order
or Relaxed Memory Order multiprocessing models do not fit well with
the C language -- C is too high-level for these. Depending on
one's compiler, though, it may be possible to insert memory barriers
and convince the compiler not to move memory operations across
those barriers, while permitting all optimizations that do not
cross such barriers. (With gcc, use "__asm__ volatile" and include
"memory" in the set of "clobbered" operands, for instance.)
I don't think of this as a memory barrier issue. I want to capture
the value that the global 'x' has at the beginning of the function,
and guarantee that exactly that same value is used later in the
function. Any changes that happen to 'x', for whatever reason, while
the function is running must not be allowed to affect what the
function does, which should depend on the value that 'x' has at function
start and not any subsequent values.

This is all *way* outside the realm of Standard C, which does not
support multiprocessing at all, and has quite limited support for
interruptions (such as signals) in a single-processing model.


Is it? I thought one of the reasons for having 'volatile' is
to enable such things as this in operating system code, which
is in fact the area of application in this case.

Thanks again for the helpful response.
Nov 14 '05 #5
On 15 Aug 2004 20:40:44 -0700, Tim Rentsch <tx*@alumnus.caltech.edu>
wrote in comp.lang.c:
Chris Torek <no****@torek.net> writes:
[lots of earlier stuff omitted]
This is not what I would consider "good style" but will achieve
the effect:

int x;
...
void f(void) {
int y = *(volatile int *)&x;
... use y as needed ...
}

Equivalently, and perhaps slightly better (but still not "great")
style:

void f(void) {
/*
* NOTE TO MAINTAINERS: references through *xp read or write
* x as if x were declared volatile, even though it is not.
* This can be used to trick the compiler into doing operations
* with partial ordering constraints without having total
* ordering constraints.
*/
volatile int *xp = &x;
int y = *xp;
... use y and/or *xp as needed ...
}


Thank you Chris for these helpful replies.

I'd thought of the 'y = *(volatile int *)&x;' before, but I concluded
it had the same problem as 'y = (volatile int)x;' -- because the
subexpression '(volatile int *)&x' isn't an lvalue (by which I mean,
can't be on the left hand side of an assignment operator), the
'volatile' type qualifier is discarded. Or do I misunderstand
what the standard means by 'lvalue'?


Yes, you did understand what is meant by 'lvalue' in this case.

The cast is on the address of x. The result of the cast is indeed an
lvalue of type 'pointer to volatile int'. The pointer itself is not
volatile, which would indeed be meaningless. But the type pointed to
by the pointer is not an lvalue, and that is what the 'volatile' in
the cast applies to.
The other solution, with 'volatile int *xp = &x;', seems to
work just fine. That's great, I hadn't thought of that.
Notice that the overall effect of this statement is no different than
the other one. In fact, you could emphasize the similarity by adding
a dreaded redundant cast to this expression:

volatile int *xp = (volatile int *)&x;

Note that the automatic conversion performed by the assignment is
exactly the same as that of the first cast expression.
Incidentally, what about this idea:

int * volatile xp = &x, y = *xp;
No, this does not do the same thing at all. Type qualifiers 'const'
and 'volatile' (and probably 'restrict', but I haven't checked) modify
what appears to their left. In this case you are defining 'xp' as a
volatile pointer to a non-volatile int.

Technically that should mean that the compiler must read the value of
the pointer xp every time you dereference it, rather than relying on a
cached value in a register or whatever. Common sense would indicate
that a compiler, needing to reread xp each time, would then
dereference it to access memory each time, but the standard does not
require this behavior.

You are unlikely to find one, but since the integer pointed to by xp
is not volatile, a compiler would be within its rights to read the
value of xp each time, compare it to a cached value, and use a cached
value for '*xp' if 'xp' itself is still the same as the last time it
was dereferenced.
Seems like that also would force actual evaluation into a
'y' temporary, even imagining a compiler smart enough to
figure out that 'y' is getting the value in 'x'. Yes?

Fundamentally, the problem is that things like Partial Store Order
or Relaxed Memory Order multiprocessing models do not fit well with
the C language -- C is too high-level for these. Depending on
one's compiler, though, it may be possible to insert memory barriers
and convince the compiler not to move memory operations across
those barriers, while permitting all optimizations that do not
cross such barriers. (With gcc, use "__asm__ volatile" and include
"memory" in the set of "clobbered" operands, for instance.)


I don't think of this as a memory barrier issue. I want to capture
the value that the global 'x' has at the beginning of the function,
and guarantee that exactly that same value is used later in the
function. Any changes that happen to 'x', for whatever reason, while
the function is running must not be allowed to affect what the
function does, which should depend on the value that 'x' has at function
start and not any subsequent values.


Any compiler that did not behave the way you describe would be
horribly broken. Don't worry about it.
This is all *way* outside the realm of Standard C, which does not
support multiprocessing at all, and has quite limited support for
interruptions (such as signals) in a single-processing model.


Is it? I thought one of the reasons for having 'volatile' is
to enable such things as this in operating system code, which
is in fact the area of application in this case.


What makes you think that the compiler is trying to optimize away a
local variable that stores the value of a file-scope object? In any
case, if the value of 'x' is subject to change while a function is
executing, and that function does not write to 'x', write via a
pointer that might alias to 'x', or call another function that might
modify 'x', that means that the value of 'x' might change
asynchronously and beyond the scope of the compiler.

In that case, 'x' should be defined as volatile in the first place.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 14 '05 #6
Tim Rentsch <tx*@alumnus.caltech.edu> writes:
[...]
I don't think of this as a memory barrier issue. I want to capture
the value that the global 'x' has at the beginning of the function,
and guarantee that exactly that same value is used later in the
function. Any changes that happen to 'x', for whatever reason, while
the function is running must not be allowed to affect what the
function does, which should depend on the value that 'x' has at function
start and not any subsequent values.


Maybe I'm oversimplifying, but I would think that simply assigning the
value to a local variable would do the trick. For example:

int x;

void foo()
{
int y = x;
...
}

References to y within foo should refer to x *only* if the compiler
can prove that they have the same value at that point -- unless the
compiler is badly broken.

The only exception would be if x can be changed by some external
mechanism that the compiler doesn't know about; in that case,
shouldn't x just be declared volatile?

I get the feeling I'm missing something.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #7
Jack Klein <ja*******@spamcop.net> writes:
On 15 Aug 2004 20:40:44 -0700, Tim Rentsch <tx*@alumnus.caltech.edu>
[stuff omitted]

I'd thought of the 'y = *(volatile int *)&x;' before, but I concluded
it had the same problem as 'y = (volatile int)x;' -- because the
subexpression '(volatile int *)&x' isn't an lvalue (by which I mean,
can't be on the left hand side of an assignment operator), the
'volatile' type qualifier is discarded. Or do I misunderstand
what the standard means by 'lvalue'?
Yes, you did understand what is meant by 'lvalue' in this case.

The cast is on the address of x. The result of the cast is indeed an
lvalue of type 'pointer to volatile int'. The pointer itself is not
volatile, which would indeed be meaningless. But the type pointed to
by the pointer is not an lvalue, and that is what the 'volatile' in
the cast applies to.


Here is my problem. The result of the cast is not an "lvalue" as I am
used to the term. Reason being, writing an assignment statement that
starts

(volatile int *) &x = ...

isn't legal. Of course it is legal if there is a '*' in front of the
cast, but that's a different expression. My best understanding now
is that the expression '(volatile int *) &x' is an 'lvalue' as the
term is used (and defined) within the C standard. If this expression
is an lvalue, then the 'volatile' qualifier is retained, and
everything works fine. And -- as I just found out -- the Rationale
has a supporting statement along these lines:

If it is necessary to access a non-volatile object using
volatile semantics, the technique is to cast the address
of the object to the appropriate pointer-to-qualified type,
then dereference the pointer.

So there you have it.

Incidentally, what about this idea:

int * volatile xp = &x, y = *xp;


No, this does not do the same thing at all. Type qualifiers 'const'
and 'volatile' (and probably 'restrict', but I haven't checked) modify
what appears to their left. In this case you are defining 'xp' as a
volatile pointer to a non-volatile int.

Technically that should mean that the compiler must read the value of
the pointer xp every time you dereference it, rather than relying on a
cached value in a register or whatever. Common sense would indicate
that a compiler, needing to reread xp each time, would then
dereference it to access memory each time, but the standard does not
require this behavior.

You are unlikely to find one, but since the integer pointed to by xp
is not volatile, a compiler would be within its rights to read the
value of xp each time, compare it to a cached value, and use a cached
value for '*xp' if 'xp' itself is still the same as the last time it
was dereferenced.


Yes, I realized this declaration was declaring the pointer as volatile
rather than what it points to. But you're right, I didn't expect that
a particularly perverse compiler could circumvent that and still be
conformant. A very interesting point - thank you.

I don't think of this as a memory barrier issue. I want to capture
the value that the global 'x' has at the beginning of the function,
and guarantee that exactly that same value is used later in the
function. Any changes that happen to 'x', for whatever reason, while
the function is running must not be allowed to affect what the
function does, which should depend on the value that 'x' has at function
start and not any subsequent values.


Any compiler that did not behave the way you describe would be
horribly broken. Don't worry about it.
This is all *way* outside the realm of Standard C, which does not
support multiprocessing at all, and has quite limited support for
interruptions (such as signals) in a single-processing model.


Is it? I thought one of the reasons for having 'volatile' is
to enable such things as this in operating system code, which
is in fact the area of application in this case.


What makes you think that the compiler is trying to optimize away a
local variable that stores the value of a file-scope object?


Sadly, because it appears that this has happened in similar cases
and that caused difficult-to-discover bugs.

As for the compiler being broken - perhaps it is, but my belief is (if
there is no mention of 'volatile') the standard allows the compiler to
behave in this way and still be conformant.

In any
case, if the value of 'x' is subject to change while a function is
executing, and that function does not write to 'x', write via a
pointer that might alias to 'x', or call another function that might
modify 'x', that means that the value of 'x' might change
asynchronously and beyond the scope of the compiler.

In that case, 'x' should be defined as volatile in the first place.


Oh, no argument there. It wasn't because of "practical considerations."
If you know what I mean.....

thanks again for the help!
Nov 14 '05 #8
Tim Rentsch <tx*@alumnus.caltech.edu> writes:
Jack Klein <ja*******@spamcop.net> writes:

[...]
What makes you think that the compiler is trying to optimize away a
local variable that stores the value of a file-scope object?


Sadly, because it appears that this has happened in similar cases
and that caused difficult-to-discover bugs.

As for the compiler being broken - perhaps it is, but my belief is (if
there is no mention of 'volatile') the standard allows the compiler to
behave in this way and still be conformant.


Given:

int x;

void foo(void)
{
int y = x;
/* ... */
... reference to y ...
}

the code generated for the reference to y can refer to y, to x, or to
the current phase of the Moon, as long as it gets the same result it
would get by actually referring to y. If references to global
variables are quicker than references to local variables (which seems
unlikely), a decent optimizing compiler is likely to transform
references to y into references to x, as long as it can prove that it
will get the same result.

In this case:

int x;

void foo(void)
{
int y = x;
x ++;
/* ... *
... reference to y ...
}

the compiler *cannot* perform this transformation; if it does, it's
violating the standard.

The transformation is forbidden in this case because x was modified by
the program itself. If the modification is done by some outside
entity that the compiler can't be expected to know about, that's a
different story; if that can happen, x should be declared volatile.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: VNG | last post by:
I have an ANSI C program that was compiled under Windows MSVC++ 6.0 (SP6) and under Linux gnu, and ran under P3, P4 and AMD. It runs fine on P3 and AMD under both Windows and Linux, but under P4...
100
by: Roose | last post by:
Just to make a tangential point here, in case anyone new to C doesn't understand what all these flame wars are about. Shorthand title: "My boss would fire me if I wrote 100% ANSI C code" We...
9
by: Tim Rentsch | last post by:
I have a question about what ANSI C allows/requires in a particular context related to 'volatile'. Consider the following: volatile int x; int x_remainder_arg( int y ){ return x % y; }
4
by: TGOS | last post by:
I was thinking about it for a while, a mutex written in C and without disabling any interrupts. Is it possible? typdef struct mutex { unsigned int owner1; unsigend int owner2; } *mutex; ...
15
by: Marc Thrun | last post by:
Hello, I've got a few questions: 1) Given the two structs struct A { int x; }; and
1
by: Eric | last post by:
I have some questions about the volatile keyword... 1) If I use the volatile keyword with a reference type such as a class like so: public volatile UserTotals totals = new UserTotals(); Are...
5
by: George2 | last post by:
Hello everyone, The following code, operator const Outer::Inner * volatile & (); 1.
16
by: Ark Khasin | last post by:
I have a memory-mapped peripheral with a mapping like, say, struct T {uint8_t read, write, status, forkicks;}; If I slap a volatile on an object of type struct T, does it guarantee that all...
8
by: Markus | last post by:
Hello everyone. Recently I stumbled upon an interesting problem related to thread-parallel programming in C (and similarily C++). As an example assume a simple "buffer" array of size 8, e.g....
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.