volatile
is not an optimization engine, and so when you used it nothing was optimized.
When you use this keyword you’re saying that this information can be changed at any time without your strict control, then what the compiler did was add an extra instruction, so it will be slower, and its function was to protect the data being used in comparison.
If what you’re saying is that there might be a change that you have no control over is just telling you not to optimize because the optimization could affect it erroneously.
If you want some optimization, then have it optimize, do it with the flag -O3
for maximum speed optimization. Nothing guarantees which optimizations will be made because the language does not require any of this, but is likely to be well simplified. The volatile
prevent optimization.
Your GCC code using O3
:
.LC0:
.string "volatile"
main:
sub rsp, 8
.L2:
mov edi, OFFSET FLAT:.LC0
xor eax, eax
call printf
jmp .L2
Behold in the Compiler Explorer.
No Clang:
main: # @main
push RBP
mov RBP, RSP
.LBB0_1: # =>This Inner Loop Header: Depth=1
mov EDI, .L.str
xor AL, AL
call printf
jmp .LBB0_1
.L.str:
.asciz "volatile"
Behold in the Compiler Explorer.
In MSVC the optimization is not done at the moment as far as I could observe.
On ARM using GCC:
main:
stp x29, x30, [sp, -32]!
mov x29, sp
str x19, [sp, 16]
adrp x19, .LC0
add x19, x19, :lo12:.LC0
.L2:
mov x0, x19
bl printf
b .L2
.LC0:
.string "volatile"
Behold in the Compiler Explorer.
Which flags you used to compile this?
– aviana
I didn’t understand your question; but to generate the Assembly code I used: gcc -S program. c
– Dead