Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Give an optimizer greater "License"

I know the concept behind volatile variables. Basically all reads and writes to that variable must occur. Is there a way to allow the optimizer to get away with only doing all of the writes and assuming that the reads will always stay the same (unless modified by writing).

Also (along the same lines) is there a way to define a new type of memory for the compiler to store variables. For example if I have a micro controller with an SD card can I define the SD card as a place to store memory (or do I explicitly have to do all of the read/writes on my own).

For the record I am using gcc as my compiler if there is anything I can do specifically (and only) on gcc

like image 836
DarthRubik Avatar asked Dec 29 '25 20:12

DarthRubik


1 Answers

I know the concept behind volatile variables.

ok...

Basically all reads and writes to that variable must occur.

Not "basically", absolutely.

Is there a way to allow the optimizer to get away with only doing all of the writes and assuming that the reads will always stay the same (unless modified by writing).

No

<- snip ->

volatile is there to model read/write access to memory mapped I/O. 'Writing' to such I/O often triggers activity in the electronics even if the value written is the same as the one previously written.

There is no other use for volatile - no, not even in multithreading (where it won't do what you wanted anyway).

From §7.1.6.1

[ Note: volatile is a hint to the implementation to avoid aggressive optimization involving the object because the value of the object might be changed by means undetectable by an implementation. Furthermore, for some implementations, volatile might indicate that special hardware instructions are required to access the object. See 1.9 for detailed semantics. In general, the semantics of volatile are intended to be the same in C++ as they are in C. — end note ]

The implication here being that unless you understand exactly what the implementation is doing with the volatile variable, you have no place using it.

It's use is not portable so if used at all, should be wrapped in an implementation-specific specialisation of whatever concept you are dealing with.

like image 188
Richard Hodges Avatar answered Dec 31 '25 13:12

Richard Hodges