How not to optimize away - mechanics of a folly function

女生的网名这么多〃 提交于 2019-11-28 23:13:30

There is no standard way to disable optimisations, so if you need to disable optimisations, you're limited to whatever your implementation happens to provide. It doesn't make sense to compare the two approaches unless you find a compiler that supports them both.

Anyway, in GCC,

asm volatile("" : "+r" (datum));

means that unverified assembly code supplied by the user is embedded into the assembly generated by GCC. The first string literal ("") contains the assembly code to inject. It's empty, so there isn't actually any code that gets emitted at all.

The part after the : informs GCC about the effect of the assembly code. "+r" (datum) means that GCC should assume that the assembly code reads and modifies datum. Even though it doesn't. The reason for that is that any earlier calculations that end up storing a value in datum cannot be discarded as unnecessary. At the same time, the assembly code itself cannot be discarded as unnecessary, because of the potential modification to datum. volatile also marks the assembly code as code that must not be optimised away, as documented here:

GCC's optimizers sometimes discard asm statements if they determine there is no need for the output variables. Also, the optimizers may move code out of loops if they believe that the code will always return the same result (i.e. none of its input values change between calls). Using the volatile qualifier disables these optimizations. [...]

It seems a bit much to use two different approaches to prevent the assembly code from being removed, really, but I guess it's best to be sure.

The r constraint means that the code does not care all that much which register GCC makes available for the assembly code to use, and is documented here:

‘r’
    A register operand is allowed provided that it is in a general register.

The + modifier means that the code may read from and write to datum, and is documented here:

‘+’
    Means that this operand is both read and written by the instruction. [...]

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!