ARM bare-metal programming in D (cont) - volatile

Mike none at none.com
Thu Oct 24 00:10:03 PDT 2013


On Thursday, 24 October 2013 at 06:41:54 UTC, Timo Sintonen wrote:
> On Thursday, 24 October 2013 at 05:37:49 UTC, Walter Bright 
> wrote:
>> On 10/23/2013 5:43 PM, Mike wrote:
>>> I'm interested in ARM bare-metal programming with D, and I'm 
>>> trying to get my
>>> head wrapped around how to approach this.  I'm making 
>>> progress, but I found
>>> something that was surprising to me: deprecation of the 
>>> volatile keyword.
>>>
>>> In the bare-metal/hardware/driver world, this keyword is 
>>> important to ensure the
>>> optimizer doesn't cache reads to memory-mapped IO, as some 
>>> hardware peripheral
>>> may modify the value without involving the processor.
>>>
>>> I've read a few discussions on the D forums about the 
>>> volatile keyword debate,
>>> but noone seemed to reconcile the need for volatile in 
>>> memory-mapped IO.  Was
>>> this an oversight?
>>>
>>> What's D's answer to this?  If one were to use D to read from 
>>> memory-mapped IO,
>>> how would one ensure the compiler doesn't cache the value?
>>
>> volatile was never a reliable method for dealing with memory 
>> mapped I/O. The correct and guaranteed way to make this work 
>> is to write two "peek" and "poke" functions to read/write a 
>> particular memory address:
>>
>>    int peek(int* p);
>>    void poke(int* p, int value);
>>
>> Implement them in the obvious way, and compile them separately 
>> so the optimizer will not try to inline/optimize them.
>
> Yes, this is a simplest way to do it and works with gdc when 
> compiled in separate file with no optimizations and inlining.
>
> But todays peripherals may have tens of registers and they are 
> usually represented as a struct. Using the peripheral often 
> require several register access. Doing it this way will not 
> make code very readable.
>
> As a workaround I have all register access functions in a 
> separate file and compile those files in a separate directory 
> with no optimizations. The amount of code generated is 3-4 
> times more and this is a problem because in controllers memory 
> and speed are always too small.

+1, This is what I feared.  I don't think D needs a volatile 
keyword, but it would be nice to have *some* way to avoid this 
overhead using language features.

I'm beginning to think inline ASM is the only way to avoid this.  
That's not a deal breaker for me, but it makes me sad.


More information about the Digitalmars-d mailing list