Help with interrupt software routine and non-atomic operations

If you write all the function code in assembler (with __asm__ volatile), it's ok. If you mix inline assembler (even with volatile) and C code, there is some risk the compiler/optimizer rearrange the instructions anyway.

For example, here is explained how to avoid rearranging, even with volatile assembler:

formatting link

Reply to
pozz
Loading thread data ...

That's a bad idea, for several reasons.

  1. You can't "switch off the optimiser". You can give a compiler hints as to how much effort it should make in optimising code, but it is only a hint - the compiler will do various optimisations and re-organisations anyway.

  1. You cannot turn bad code into good code by fiddling with optimiser options. Write your code /correctly/, according to the rules of C and the additional facilities provided by individual compilers, and let the optimiser do its job. If your code "works when optimisation is disabled", then you can be pretty sure that your code is bad.

  2. With -O0 optimisation, gcc (and many other compilers) produce terribly inefficient code. That helps no one.

  1. Mixing optimisation levels in different functions in one translation unit works poorly. The compiler does not handle functions completely separately, so different options have a tendency to "rub off" on other functions. So you will get some optimisations unexpectedly enabled in this one function, and others unexpectedly disabled in other functions.

See above (and Reinhardt's point below).

No, we don't. We need tools for telling the compiler about the code in more detail than the C language provides - and asking the compiler to give us the best code it can within those additional restrictions. "volatile" is a good step here. Memory clobbers are an additional tool, though the details are specific to each compiler, and they are quite coarse-grained.

That is part of it, but it is not the only one.

I should hope that the compiler will re-arrange and optimise the inline assembler - that is one of the features of gcc that beats many commercial tools that get flustered and panic whenever they see assembly code. The fact that the compiler will handle inline assembly within the flow of the optimiser and the surrounding C code lets you use target-specific features without losing basic C optimisations or having to write large chunks of performance-critical code in manual assembly.

But it does mean that you have to learn to understand how to talk to your compiler if you want the very best quality code, and are not satisfied by simply adding a generous selection of "volatile" qualifiers.

Reply to
David Brown

ElectronDepot website is not affiliated with any of the manufacturers or service providers discussed here. All logos and trade names are the property of their respective owners.