2

In Windows, can __asm nop be swapped for asm volatile("nop"); (used in GCC compiler) and yield the same result?

I have read that volatile() (in GCC) guarantees the call will not be optimized away. However, it doesn't port directly to Windows, and I was curious if it can simply be removed or if it needs to be replaced with a similar construct.

Zak
  • 12,213
  • 21
  • 59
  • 105
  • It's a `nop` instruction, which explicitly does *nothing*. You might need to give a little more context to reveal why it might have been included in the first place. – Greg Hewgill Sep 16 '14 at 21:45
  • 2
    The MSVC++ code optimizer doesn't mess with inline assembly. So, yes. – Hans Passant Sep 16 '14 at 21:46
  • @GregHewgill It is my understanding, if you use the volatile command in GCC, it will not be optimized away, and allows various kinds of functionality (i.e. non-locking data-structures, etc). I should also mention, it is not my concern why someone would chose to write this code, only how I can port it over with the same results. – Zak Sep 16 '14 at 21:48
  • @HansPassant Please site your response and put that in an answer, so I can accept it. Thanks! – Zak Sep 16 '14 at 21:49

2 Answers2

2

The __asm keyword implementation is quite simplistic in MSVC. It always emits the machine code unaltered and the optimizer doesn't touch it. Nor does it make any assumptions about machine state after the __asm, that has a knack for defeating other optimizations.

So, no, nothing similar to volatile() is required, it can't disappear. Plain __asm { nop } will always survive unscathed and is equivalent to the GCC assembly.

Do keep in mind that inline assembly is not a good long-term strategy, support for it was removed completely in the x64 compiler and is pretty unlikely to ever come back. You'll have to fall back to intrinsics or link code written in assembly and compiled with, say, ml64.exe. That does defeat NOP injection, but code alignment is already well taken care of by the optimizer and doesn't need help. Also the reason you probably should not do this at all.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
1

For the Microsoft compiler, use the __nop() intrinsic function to emit a nop instruction without handicapping the compiler's optimizer. This would also be cross-platform across all Windows targets (32 bit ARM V7, 64 bit ARM V8, IA32, X64).

ahcox
  • 9,349
  • 5
  • 33
  • 38