6

On the x86, can someone confirm, whether or not a zero displacement jump (i.e. a jump that doesn't alter the values in CS or IP) clears the Instruction Prefetch Queue?

Johan
  • 74,508
  • 24
  • 191
  • 319

1 Answers1

8

A jump to the next statement that would have been executed anyways does clear the instruction prefetch queue on any Intel x86 CPU that has one. It was a common to do so in self-modifying code in order to ensure that modified code was actually executed. Intel has gone so far as to document using a jump as means to ensure that self-modified code gets executed correctly even on modern CPUs.

From Intel 64 and IA-32 Architectures Software Developer’s Manual Volume 3: System Programming Guide:

8.1.3 Handling Self- and Cross-Modifying Code

...

As processor microarchitectures become more complex and start to speculatively execute code ahead of the retirement point (as in P6 and more recent processor families), the rules regarding which code should execute, pre- or post-modification, become blurred. To write self-modifying code and ensure that it is compliant with current and future versions of the IA-32 architectures, use one of the following coding options:

(* OPTION 1 *)
Store modified code (as data) into code segment;
Jump to new code or an intermediate location;
Execute new code;

(Option 2 is to use a serializing instruction instead of a jump, but these don't exist on early x86 CPUs.)

Community
  • 1
  • 1
Ross Ridge
  • 38,414
  • 7
  • 81
  • 112
  • Fun fact: you can't test whether or not you've satisfied the on-paper ISA requirement (unless you have a physical ancient CPU to test on), because modern x86 CPUs have stronger snooping to detect and handle self-modifying code with a pipeline nuke. [Observing stale instruction fetching on x86 with self-modifying code](https://stackoverflow.com/a/18388700). On *modern* out-of-order CPUs, SMC always Just Works with no jump needed. But yes, the ISA rules say any jump is safe, so that's what you should do (unless you were going to use a serializing insn anyway.) – Peter Cordes Jan 07 '19 at 03:33