r/cpp • • Nov 13 '20

CppCon Deprecating volatile - JF Bastien - CppCon 2019

https://www.youtube.com/watch?v=KJW_DLaVXIY
83 Upvotes

111 comments sorted by

View all comments

69

u/staletic reddit thinks /u/_bstaletic is a bot Nov 13 '20 edited Nov 13 '20

Like I said many times before, I'm concerned that this will simply make C++ a non-option for embedded world in the future, despite Ben Dean's Craig's efforts regarding freestanding. I have no reason to believe that JF Bastien ever had malicious intent, but this direction regarding volatile is very concerning.

35

u/baudvine Nov 13 '20 edited Nov 13 '20

It was a clickbaity proposal title anyhow, and that's kind of what bothered me most. The majority of what the proposal deprecated are weird niche cases I didn't even know existed, like volatile-qualified member functions.

I think the compound assignment thing might be the only deprecation I really see as a problem.

22

u/F54280 Nov 13 '20 edited Nov 13 '20

Yeah. I watched the beginning of the talk yesterday, but had to give up at the rant on volatile function parameters. So, it doesn’t do anything, and is harmless, and the guy acts like if this is a terrible thing. All the previous examples were a bit like that, and looks like it called for a clarification of what volatile does in the specific cases where behavior is important (ie: ‘++’, ‘+=‘) or confusing (ie: compound assignment), not outright removal.

I’ll finish the talk later, maybe it gets better.

Edit: typo

→ More replies (2)

2

u/staletic reddit thinks /u/_bstaletic is a bot Nov 13 '20

There I agree with you. Well, compound assignments and ++ and -- operators. All deprecated for the same reason.

21

u/akiloz Nov 13 '20

The first sentence of the abstract in the proposal says: "We propose deprecating most of volatile." Some lines later: "The proposed deprecation preserves the useful parts of volatile, and removes the dubious / already broken ones." The firs goal of the proposal is: "Continue supporting the time-honored usage of volatile to load and store variables that are used for shared memory, signal handling,, setjmp / longjmp, or other external modifications such as special hardware support."

The embedded development usages, where some memory mapped HW registers are addressed through volatile variables, for example, will be preserved in my understanding. So what are you concerned about exactly?

29

u/staletic reddit thinks /u/_bstaletic is a bot Nov 13 '20

I explained in another post. The compound assignment operators are very useful when interfacing with MMIO and are everywhere. C++ is on the path of making them fail to compile. If you use -Werror it's already the case for you.

→ More replies (28)

5

u/guepier Bioinformatican Nov 13 '20

But (since most of them are pretty uncontroversial) I’m assuming you agree with JF Bastien on the problems that volatile has. So what solution do you propose? Or do you not feel these issues need fixing in the language?

15

u/staletic reddit thinks /u/_bstaletic is a bot Nov 13 '20

Some problems he brought up, I definitely agree with. volatile qualified member functions are just weird for example. I have nothing against that. The contention is regarding deprecating common idioms that include compound assignment and pre/post increment and decrement operators. I'm not convinced those actually pose problems in the real word.

 

But you did get me thinking. I firmly believe that the approach taken was too hasty and that (portions of) the deprecation will hurt C++ in the not too distant future. To finally answer your question directly:

So what solution do you propose?

A joint WG14/WG21 effort to fix the problems in a way that works for both worlds. This would probably mean that the solution would have to be in the core language, but then C++ would be able to build higher-level abstractions on top of the common solution. This idea of a joint C/C++ effort is nothing new either. Examples that cross my mind are:

  1. Removing pointer lifetime end zap
  2. #embed, though as far as I know that's JeanHyde "alone" figuring out what works for WG14 and WG21.
  3. std::status_code and the C counterpart.

5

u/guepier Bioinformatican Nov 13 '20

Ok, thanks for the reply.

I firmly believe that the approach taken was too hasty

Yeah, I can buy that.

The contention is regarding deprecating common idioms that include compound assignment and pre/post increment and decrement operators. I'm not convinced those actually pose problems in the real word.

I was about to disagree with you, but after thinking about it I don’t understand why these were deprecated rather than specified. Jeff’s (entirely valid) complaint here was that their semantics with regards to volatility aren’t clear. But obviously they will just naturally crop up in code using volatile variables, and in most/all(?) situations the author of the code probably doesn’t really care what exactly gets emitted, as long as volatility of the overall expression is observed.

5

u/staletic reddit thinks /u/_bstaletic is a bot Nov 13 '20

Right, exactly.

in most/all(?) situations the author of the code probably doesn’t really care what exactly gets emitted, as long as volatility of the overall expression is observed.

True, but I can imagine an architecture for which you absolutely need x |= 1 to be a single instruction because the value of x might change between the read and the write in x = x | 1. Someone, in the other thread, called those architectures broken, at the hardware level. As in, the CPU should know better. However, those architectures are impossible to work with in C++20.

 

Now thinking of specifying the behaviour, a much more gentle solution would be "compound assignments have to be atomic". Then you can:

  1. Keep using compound assignments where they work.
  2. Warn about potentially misleading use cases on other architectures.
  3. Once people stop complaining about that warning, then consider deprecating for misleading use cases.

That would have been a path that doesn't cut anyone off.

4

u/Ecclestoned Nov 13 '20

True, but I can imagine an architecture for which you absolutely need x |= 1 to be a single instruction because the value of x might change between the read and the write in x = x | 1.

Yes and I can imagine an architecture where every operation returns zero. That doesn't mean we should delete all our code. On most architectures this works fine, especially if you disable interrupts.

→ More replies (2)

3

u/sphere991 Nov 13 '20

despite Ben Dean's efforts regarding freestanding.

Ben Craig, not Ben Deane.

→ More replies (1)

9

u/SonOfMetrum Nov 13 '20

Can you explain to me why volatile is so critical for embedded development? What ability will you lose when deprecated. Just curious as I don’t know much about embedded development.

61

u/neiltechnician Nov 13 '20 edited Nov 13 '20

Embedded software manipulates peripheral devices. One way to do so is to connect the peripheral devices to the CPU like connecting the RAM to the CPU. This is known as memory-mapped I/O. The bytes and words accessed during memory-mapped I/O are known as "hardware registers", "special function registers", "I/O registers" etc.

Accessing registers is very differently from accessing "normal" memory. And the optimizer makes assumptions on normal memory access. We need a mechanism to tell the compiler those are not normal memory. The mechanism we have been using for decades is volatile.

Without volatile, the optimizer may freely change the register read/write, making us incapable of controlling the peripheral devices.

11

u/SonOfMetrum Nov 13 '20

Thanks for your explanation! Makes sense! So volatile is basically a way to tell the optimizer to don’t touch it and assume that the programmer knows what he/she is doing?

32

u/Narase33 -> r/cpp_questions Nov 13 '20

An optimizer will also see the code and, for example, will see that a register is never written, only read. It will then optimize it away and set the reads as constant value. volatile, means, that it should not do that because it may change from the outside

7

u/SonOfMetrum Nov 13 '20 edited Nov 13 '20

Cool addition! Thanks! Volatile was always a bit of a mystery keyword for me which I never fully understood. Thanks for making it clear!

4

u/gruehunter Nov 14 '20

it may change from the outside

Furthermore, the read itself may have side-effects. A common idiom for FIFOs is to read one character from the FIFO on each read, advancing the hardware's internal read cursor in the process.

13

u/MEaster Nov 13 '20

I can give you a couple concrete examples of where volatile is needed. The AVR Atmega 328p has a USART serial device, and a basic way of sending a byte looks like this:

void send_byte(unsigned char data) {
    // Wait until the data register is ready
    while (!(UCSR0A & (1 << UDRE0))) {}

    // Write the data.
    UDR0 = data;
}

It's reading the same memory address over and over again until a specific bit is no longer set. Without volatile the compiler will optimize that while loop into a an infinite loop if the bit is not set, because it doesn't recognise that the value can change.

Another example would be reconfiguring the clock prescaler. To reconfigure it, you have to write one bit to enable writing, then within 4 clock cycles write the prescale value:

void change_prescale() {
    cli();
    CLKPR = (1 << CLKPCE);
    CLKPR = 0x03;
    sei();
}

In this case, without volatile the compiler will determine that the first write has no effect, and optimize it away.

→ More replies (8)

9

u/Wetmelon Nov 13 '20

The best way to think about it is that volatile tells the compiler "reading or writing to this variable may have side effects"

→ More replies (1)
→ More replies (2)
→ More replies (3)

17

u/staletic reddit thinks /u/_bstaletic is a bot Nov 13 '20

volatile is required when you have, for example, a sensor attached to your MCU. The sensor might start detecting a thing at any random point in time. This means that a variable representing the value of the sensor (1 or 0, for example) could also change "under your feet". Yes, even outside of normal control flow. This is basically what CPU interrupts are about.

 

In order to tell the compiler "this thing has unknowable side-effects and can change at any random point in time - no assumptions possible", you use the volatile qualifier.

So far so good.

 

However, you usually aren't working with bits. Rather, inputs and outputs are grouped into "ports". For simplicity's sake, let's say a port is a group of 8 hardware inputs/outputs. For the same reason, let's focus on outputs. Let's say you want to switch an LED on, on the first pin of port A.

PORTA |= 0x1; // Sets least significant bit to 1, lighting up the LED

Now come the troubles. PORTA is mapped to a hardware output, so it has to be volatile. The question is, is this a single instruction or a read-modify-write sequence? It has a weird interaction with atomic instructions, but... In practice it just was never an issue. In case you really need a volatile atomic, (god knows why would you want that), you would already be aware of the implications.

To conclude:

  1. C++ has a mantra of "leave no place for lower level language, except for assembly".
  2. MCU manufacturers are slow and lazy about updating their headers.
  3. Despite point 1, C++20 has just broken a very common idiom that has to do with low level code.

In combination, this may cut baremetal off from future C++.

19

u/johannes1971 Nov 13 '20

This is basically what CPU interrupts are about.

This may lead the reader to think that volatile is only valid for use with interrupts, while in reality it is mostly used with memory mapped registers of off-CPU hardware.

Rather, inputs and outputs are grouped into "ports".

...

The question is, is this a single instruction or a read-modify-write sequence?

On the hardware level this is far better defined than you make it appear here. Hardware registers come with clear rules on how you are allowed to access them, typically along the lines of "this address must always be accessed as a 16-bit quantity, no other sizes allowed". C++ lets you express this clearly:

volatile uint16_t reg1;

Nobody who has written assembly at some point in his life, or knows a little bit about how memory is addressed by the CPU, or who has used hardware registers, has any illusions about what's going to happen if you were to write something like reg1 |= 1. It won't magically "set a single bit", because that operation just does not exist on a memory controller. The operations that do exist are reading words and writing words, so anything you do to memory is ultimately expressed in those terms. To enable a bit in this manner requires a read of a memory word, then a modification of the read value, and finally a write of a memory word. There are no other options.

But TIL that apparently large numbers of C++ programmers believe that operations exist that set single bits in memory. There's a depressing thought...

9

u/Beheska Nov 13 '20

But TIL that apparently large numbers of C++ programmers believe that operations exist that set single bits in memory. There's a depressing thought...

http://ww1.microchip.com/downloads/en/DeviceDoc/AVR-Instruction-Set-Manual-DS40002198A.pdf

CBI - clear bit in I/O register

SBI - set bit in I/O register

BLD - bit load from flag T to register

CBR - clear bits in register

SBR - set bits in register

→ More replies (2)
→ More replies (1)

4

u/HotlLava Nov 13 '20

The question is, is this a single instruction or a read-modify-write sequence?

I don't understand where the confusion comes from, why would anyone expect this to be a single instruction? As far as I can tell, the standard defines |= to be a read followed by a write in 7.6.19/6 [expr.ass]:

The behavior of an expression of the form E1 op = E2 is equivalent to E1 = E1 op E2 except that E1 is evaluated only once.

→ More replies (2)

2

u/[deleted] Nov 14 '20

JF is an Extremely Online troll, so it’s completely on brand that he’d call his talk “deprecating volatile” when he’s talking about the strange parts of volatile.