x86 CPU是否仅对Load和Store指令重排序,其余指令不重排?
Great question! Let's unpack this clearly, since x86's memory model is one of the stricter ones out there compared to ARM or PowerPC.
First, let's clarify two different types of instruction reordering we're talking about: memory visibility-related reordering (the kind that matters for multi-threaded code and shared variables) and general out-of-order execution (CPU optimizations to speed up single-threaded performance).
Memory Visibility Reordering (The "Memory Ordering" You're Asking About)
When articles talk about memory ordering and x86, they're almost always referring to reordering of memory access instructions (Loads = reading from memory, Stores = writing to memory). For this category, x86 follows the Total Store Order (TSO) model, which has strict rules:
- Loads are never reordered with other Loads
- Stores are never reordered with other Stores
- Stores are never reordered with older Loads
- The only allowed memory reordering is Loads can be reordered with older Stores to different memory addresses
So for multi-threaded code where shared memory visibility is critical, yes—x86 only reorders Load and Store instructions, and even then only in that specific allowed case. Other instruction types (like arithmetic, logic, or control-flow) don't factor into memory ordering because they don't interact with shared memory in a way that affects cross-thread visibility.
General Out-of-Order Execution (Non-Memory Instruction Reordering)
That said, x86 CPUs absolutely do reorder other types of instructions for performance—but this is part of their out-of-order execution pipeline, not memory ordering. The CPU will rearrange independent instructions (like arithmetic operations, bitwise logic, or even some branch-related instructions) as long as it doesn't violate the as-if rule: the final result of the program must be exactly the same as if instructions ran in the original sequential order.
For example:
- If you have a slow multiplication instruction waiting on data from memory, the CPU might run a subsequent independent addition instruction first to keep the pipeline busy.
- These reorders are invisible to single-threaded code and don't affect multi-threaded memory visibility, since they don't involve shared memory accesses.
Bottom Line
If your question is focused on memory ordering for multi-threaded code (the context where "memory ordering" is usually discussed), then yes—x86 only reorders Load and Store instructions (with strict limitations). If you're talking about general CPU instruction reordering for performance, then non-memory instructions are absolutely reordered, but this doesn't impact the memory model rules you've read about.
内容的提问来源于stack exchange,提问作者James

