17 comments

  • sparkie1 minute ago
    &gt; x86 is unusual in mostly having a maximum of two operands per instruction[2]<p>Perhaps interesting for those who aren&#x27;t up to date, the new APX extension allows 3-operand versions of most of the ALU instructions with a new data destination, so we don&#x27;t need to use temporary registers - making them more RISC-like.<p>The downside is they&#x27;re EVEX encoded, which adds a 4-byte prefix to the instruction.<p><a href="https:&#x2F;&#x2F;www.intel.com&#x2F;content&#x2F;www&#x2F;us&#x2F;en&#x2F;developer&#x2F;articles&#x2F;technical&#x2F;advanced-performance-extensions-apx.html" rel="nofollow">https:&#x2F;&#x2F;www.intel.com&#x2F;content&#x2F;www&#x2F;us&#x2F;en&#x2F;developer&#x2F;articles&#x2F;t...</a>
  • pansa28 hours ago
    &gt; <i>Using `lea` […] is useful if both of the operands are still needed later on in other calculations (as it leaves them unchanged)</i><p>As well as making it possible to preserve the values of both operands, it’s also occasionally useful to use `lea` instead of `add` because it preserves the CPU flags.
    • andrepd8 hours ago
      Funny to see a comment on HN raising this exact point, when just ~2 hours ago I was writing inline asm that used `lea` precisely to preserve the carry flag before a jump table! :)
      • MYEUHD7 hours ago
        I&#x27;m curious, what are you working on that requires writing inline assembly?
        • veltas6 hours ago
          I&#x27;m not them but whenever I&#x27;ve used it it&#x27;s been for arch specific features like adding a debug breakpoint, synchronization, using system registers, etc.<p>Never for performance. If I wanted to hand optimise code I&#x27;d be more likely to use SIMD intrinsics, play with C until the compiler does the right thing, or write the entire function in a separate asm file for better highlighting and easier handing of state at ABI boundary rather than mid-function like the carry flags mentioned above.
          • vlovich1233 hours ago
            Generally inline assembly is much easier these days as a) the compiler can see into it and make optimizations b) you don’t have to worry about calling conventions
            • Someone2 hours ago
              &gt; the compiler can see into it and make optimizations<p>Those writing assembler typically&#x2F;often think&#x2F;know they can do better than the compiler. That means that isn’t necessarily a good thing.<p>(Similarly, <i>veltas</i> comment above about <i>“play with C until the compiler does the right thing”</i> is brittle. You don’t even need to change compiler flags to make it suddenly not do the right thing anymore (on the other hand, when compiling for a different version of the CPU architecture, the compiler <i>can</i> fix things, too)
              • kragen1 hour ago
                It&#x27;s rare that I see compiler-generated assembly without obvious drawbacks in it. You don&#x27;t have to be an expert to spot them. But frequently the compiler also finds improvements I wouldn&#x27;t have thought of. We&#x27;re in the centaur-chess moment of compilers.<p>Generally playing with the C until the compiler does the right thing is slightly brittle in terms of performance but not in terms of functionality. Different compiler flags or a different architecture may give you worse performance, but the code will still work.
              • veltas2 hours ago
                &gt; “play with C until the compiler does the right thing” is brittle<p>It&#x27;s brittle depending on your methods. If you understand a little about optimizers and give the compiler the hints it needs to do the right things, then that should work with any modern compiler, and is more portable (and easier) than hand-optimizing in assembly straight away.
        • vardump6 hours ago
          Might be an interpreter or an emulator. That’s where you often want to preserve registers or flags and have jump tables.<p>This is one of the remaining cases where the current compilers optimize rather poorly: when you have a tight loop around a huge switch-statement, with each case-statement performing a very small operation on common data.<p>In that case, a human writing assembler can often beat a compiler with a huge margin.
          • pedrocr4 hours ago
            I&#x27;m curious if that&#x27;s still the case generally after things like musttail attributes to help the compiler emit good assembly for well structured interpreter loops:<p><a href="https:&#x2F;&#x2F;blog.reverberate.org&#x2F;2025&#x2F;02&#x2F;10&#x2F;tail-call-updates.html" rel="nofollow">https:&#x2F;&#x2F;blog.reverberate.org&#x2F;2025&#x2F;02&#x2F;10&#x2F;tail-call-updates.ht...</a>
        • gishh4 hours ago
          I worked on a C codebase once, integrating an i2c sensor. The vendor only had example code in asm. I had to learn to inline asm.<p>It still happens in 2025
      • AI-NoGuardrails4 hours ago
        [flagged]
  • sethops18 hours ago
    This guy is tricking us into learning assembly! Get &#x27;em!!
  • greatgib8 hours ago
    As a side note of appreciation, I think that we can&#x27;t do better than what he did for being transparent that LLM was used but still just for the proof-reading.
    • quietbritishjim5 hours ago
      Agreed that it&#x27;s nice he acknowledged it, but proof reading is about as innocuous of a task for LLMs as they come. Because you actually wrote the content and know its meaning (or at least intended meaning), you can instantly tell when to discard anything irrelevant from the LLM. At worst, it&#x27;s no better than just skipping that review step.
    • jfindper6 hours ago
      It does make me curious about the what the super anti-ai people will do.<p>Matt Godbolt is, obviously, <i>extremely</i> smart and has a lot of interesting insight as a domain expert. <i>But</i>... this was LLM-assisted.<p>So, anyone who has previously said they&#x27;ll never (knowingly) read anything that an ai has touched (or similar sentiment) are you going to skip this series? Make an exception?
      • joaohaas5 hours ago
        I think most people wouldn&#x27;t call proof-reading &#x27;assistance&#x27;. As in, if I ask a colleague to review my PR, I wouldn&#x27;t say he assisted me.<p>I&#x27;ve been throwing my PR diffs at Claude over the last few weeks. It spits a <i>lot</i> of useless or straight up wrong stuff, but sometimes among the insanity it manages to get one or another typo that a human missed, and between letting a bug pass or spending extra 10m per PR going through the nothingburguers Claude throws at me, I&#x27;d rather lose the 10m.
  • mordechai90006 hours ago
    This triggers a vague memory of trying to figure out why my assembler (masm?) was outputting a LEA instead of a MOV. I can&#x27;t remember why. Maybe LEA was more efficient, or MOV didn&#x27;t really support the addressing mode and the assembler just quietly fixed it for you.<p>In any case, I felt slightly betrayed by the assembler for silently outputting something I didn&#x27;t tell it to.
    • HarHarVeryFunny5 hours ago
      LEA and MOV are doing different things. LEA is just calculating the effective address, but MOV calculates the address then retrieves the value stored at that address.<p>e.g. If base + (index * scale) + offset = 42, and the value at address 42 is 3, then:<p>LEA rax, [base + index * scale + offset] will set rax = 42<p>MOV rax, [base + index * scale + offset] will set rax = 3
      • dataflow5 hours ago
        I assumed they&#x27;re referring to register-register moves?
        • HarHarVeryFunny4 hours ago
          OK, so:<p>LEA eax, [ebx]<p>instead of:<p>MOV eax, ebx<p>But of course:<p>MOV eax, [ebx]<p>is not the same.
  • miningape9 hours ago
    Loving this series! I&#x27;m currently implementing a z80 emulator (gameboy) and it&#x27;s my first real introduction to CISC, and is really pushing my assembly &#x2F; machine code skills - so having these blog posts coming from the &quot;other direction&quot; are really interesting and give me some good context.<p>I&#x27;ve implemented toy languages and bytecode compilers&#x2F;vms before but seeing it from a professional perspective is just fascinating.<p>That being said it was totally unexpected to find out we can use &quot;addresses&quot; for addition on x86.
    • Joker_vD8 hours ago
      A seasoned C programmer knows that &quot;&amp;arr[index]&quot; is really just &quot;arr + index&quot; :) So in a sense, the optimizer rewrote &quot;x + y&quot; into &quot;(int)&amp;(((char*)x)[y])&quot;, which looks scarier in C, I admit.
      • crote8 hours ago
        The horrifying side effect of this is that &quot;arr[idx]&quot; is equal to &quot;idx[arr]&quot;, so &quot;5[arr]&quot; is just as valid as &quot;arr[5]&quot;.<p>Your colleagues would probably prefer if you forget this.
        • miningape7 hours ago
          Mom, please come pick me up. These kids are scaring me.
        • Joker_vD8 hours ago
          &gt; so &quot;5[arr]&quot; is just as valid as &quot;arr[5]&quot;<p>This is, I am sure, one of the stupid legacy reasons we still write &quot;lr a0, 4(a1)&quot; instead of more sensible &quot;lr a0, a1[4]&quot;. The other one is that FORTRAN used round parentheses for both array access and function calls, so it stuck somehow.
          • kragen1 hour ago
            Generally such constant offsets are record fields in intent, not array indices. (If they were array indices, they&#x27;d need to be variable offsets obtained from a register, not immediate constants.) It&#x27;s reasonable to think of record fields as functions:<p><pre><code> .equ car, 0 .equ cdr, 8 .globl length length: test %rdi, %rdi # nil? jz 1f # return 0 mov cdr(%rdi), %rdi # recurse on tail of list call length inc %rax ret 1: xor %eax, %eax ret </code></pre> To avoid writing out all the field offsets by hand, ARM&#x27;s old assembler and I think MASM come with a record-layout-definition thing built in, but gas&#x27;s macro system is powerful enough to implement it without having it built into the assembler itself. It takes about 13 lines of code: <a href="http:&#x2F;&#x2F;canonical.org&#x2F;~kragen&#x2F;sw&#x2F;dev3&#x2F;mapfield.S" rel="nofollow">http:&#x2F;&#x2F;canonical.org&#x2F;~kragen&#x2F;sw&#x2F;dev3&#x2F;mapfield.S</a><p>Alternatively, on non-RISC architectures, where the immediate constant isn&#x27;t constrained to a few bits, it can be the address of an array, and the (possibly scaled) register is an index into it. So you might have startindex(,%rdi,4) for the %rdi&#x27;th start index:<p><pre><code> .data startindex: .long 1024 .text .globl length length: mov (startindex+4)(,%rdi,4), %eax sub startindex(,%rdi,4), %eax ret </code></pre> If the PDP-11 assembler syntax had been defined to be similar to C or Pascal rather than Fortran or BASIC we would, as you say, have used startindex[%rdi,4].<p>This is not very popular nowadays both because it isn&#x27;t RISC-compatible and because it isn&#x27;t reentrant. AMD64 in particular is a kind of peculiar compromise—the immediate &quot;offset&quot; for startindex and endindex is 32 bits, even though the address space is 64 bits, so you could conceivably make this code fail to link by placing your data segment in the wrong place.<p>(Despite stupid factionalist stuff, I think I come down on the side of preferring the Intel syntax over the AT&amp;T syntax.)
          • beng-nl4 hours ago
            Yes, I find this one of the weird things about assembly - appending (or pretending?) a number means addition?! - even after many many years of occasionally reading&#x2F;writing assembly, I’m never completely sure what these instructions do so I infer from context.
        • rocqua8 hours ago
          That depends on sizeof(*arr) no?
          • unwind7 hours ago
            Not in C no, since arithmetic on a pointer is implicitly scaled by the size of the value being pointed at (this statement is kind of breaking the abstraction ... oh well).
          • messe7 hours ago
            Nope, a[b] is equivalent to *(a + b) regardless of a and b.
            • sureglymop7 hours ago
              Given that, why don&#x27;t we use just `*(a + b)` everywhere?<p>Wouldn&#x27;t that be more verbose and less confusing? (genuinely asking)
              • tomsmeding6 hours ago
                Do you really think that `*(a + i)` is clearer than `a[i]`?
                • sureglymop4 hours ago
                  Not necessarily. I think it&#x27;s confusing when there are two fairly close ways to express the same thing.
  • stassats6 hours ago
    The text mentions that it can also do multiplication but doesn&#x27;t expand on that.<p>E.g. for x * 5 gcc issues lea eax, [rdi+rdi*4].
    • xg151 hour ago
      It also says the multiplier must be one of 2, 4 or 8.<p>So I guess this trick then only works for multiplication by 2, 3, 4, 5, 8 or 9?
      • stassats40 minutes ago
        The tricks to avoid multiplication (and division) are probably worth a whole post.<p><pre><code> x * 6: lea eax, [rdi+rdi*2] add eax, eax x * 7: lea eax, [0+rdi*8] sub eax, edi x * 11: lea eax, [rdi+rdi*4] lea eax, [rdi+rax*2] </code></pre> But with -Os you get imul eax, edi, 6<p>And on modern CPUs multiplication might not be actually all that slow (but there may be fewer multiply units).
  • badmonster2 hours ago
    LEA is a beautiful example of instruction reuse. Designed for pointer arithmetic, repurposed for efficient addition. It&#x27;s a reminder that good ISA design leaves room for creative optimization - and that compilers can find patterns human assembly programmers might miss.
    • kragen2 hours ago
      Human assembly programmers on the 8086 used LEA all the fucking time. And I&#x27;m not sure good ISA design is characterized by the need for ingenious hacks to get the best mileage out of the hardware; rather the opposite, in my view. The ARM2&#x27;s ISA design is head and shoulders better than the 8086&#x27;s.
  • Thorrez8 hours ago
    &gt;However, in this case it doesn’t matter; those top bits5 are discarded when the result is written to the 32-bit eax.<p>&gt;Those top bits should be zero, as the ABI requires it: the compiler relies on this here. Try editing the example above to pass and return longs to compare.<p>Sorry, I don&#x27;t understand. How could the compiler both discard the top bits, and also rely on the top bits being zero? If it&#x27;s discarding the top bits, it won&#x27;t matter whether the top bits are zero or not, so it&#x27;s not relying on that.
    • Joker_vD8 hours ago
      (Almost) any instruction on x64 that writes to a 32-bit register as destination, writes the lower 32-bits of the value into the lower 32 bits of the full 64-bit register and zeroes out the upper 32 bits of the full register. He touched on it in his previous note &quot;why xor eax, eax&quot;.<p>But the funny thing is, the x64-specific supplement for SysV ABI doesn&#x27;t actually specify whether the top bits should be zeroes or not (and so, if the compiler could rely on e.g. function returning ints to have upper 32 bits zeroes, or those could be garbage), and historically GCC and Clang diverged in their behaviour.
    • 2019848 hours ago
      He&#x27;s actually wrong on the ABI requiring the top bits to be 0. It only requires that the bottom 32 bits match the parameter, but the top bits of a 32-bit parameter passed in a 64-bit register can be anything (at least on Linux).<p>You can see that in this godbolt example: <a href="https:&#x2F;&#x2F;godbolt.org&#x2F;z&#x2F;M1ze74Gh6" rel="nofollow">https:&#x2F;&#x2F;godbolt.org&#x2F;z&#x2F;M1ze74Gh6</a><p>The reason the code in his post works is because the upper 32 bits of the parameters going into an addition can&#x27;t affect the low 32 bits of the result, and he&#x27;s only storing the low 32 bits.
      • fweimer7 hours ago
        The LLVM x86-64 ABI requires the top bits to be zero. GCC treats them as undefined. Until a recent clarification, the x86-64 psABI made the upper bits undefined by omission only, which is why I think most people followed the GCC interpretation.<p><a href="https:&#x2F;&#x2F;github.com&#x2F;llvm&#x2F;llvm-project&#x2F;issues&#x2F;12579" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;llvm&#x2F;llvm-project&#x2F;issues&#x2F;12579</a> <a href="https:&#x2F;&#x2F;groups.google.com&#x2F;g&#x2F;x86-64-abi&#x2F;c&#x2F;h7FFh30oS3s&#x2F;m&#x2F;Gksanh3WAAAJ" rel="nofollow">https:&#x2F;&#x2F;groups.google.com&#x2F;g&#x2F;x86-64-abi&#x2F;c&#x2F;h7FFh30oS3s&#x2F;m&#x2F;Gksan...</a> <a href="https:&#x2F;&#x2F;gitlab.com&#x2F;x86-psABIs&#x2F;x86-64-ABI&#x2F;-&#x2F;merge_requests&#x2F;61" rel="nofollow">https:&#x2F;&#x2F;gitlab.com&#x2F;x86-psABIs&#x2F;x86-64-ABI&#x2F;-&#x2F;merge_requests&#x2F;61</a>
        • account425 hours ago
          GCC is the one defining the effective ABI here so LLVM was always buggy no matter what the spec said &#x2F; didn&#x27;t say.
          • gpderetta4 hours ago
            Actually not, the ABI is a cross vendor initiative.
      • jfindper7 hours ago
        There is something fun about using godbolt.org to say that Matt Godbolt is wrong.
  • xjm6 hours ago
    Part of the Advent of Compiler Optimisations <a href="https:&#x2F;&#x2F;xania.org&#x2F;AoCO2025" rel="nofollow">https:&#x2F;&#x2F;xania.org&#x2F;AoCO2025</a><p>Loving it so far!
  • zahlman3 hours ago
    It&#x27;s still wild to me that &quot;Godbolt&quot; is an actual surname.
    • xg151 hour ago
      Someone had a very talented archer as an ancestor.
  • egurns5 hours ago
    &gt; Yesterday we saw how compilers zero registers efficiently.<p>It took several tries to understand <i>zero</i> is a verb
    • kragen1 hour ago
      Often I use &quot;zeroize&quot; rather than &quot;zero&quot; to avoid such confusion.
    • delta_p_delta_x3 hours ago
      It might have been a <i>little</i> bit clearer to say:<p><pre><code> Yesterday we saw how compilers zero out registers efficiently. </code></pre> Or better still:<p><pre><code> Yesterday we saw how compilers set the values in registers to zero efficiently.</code></pre>
    • gbacon5 hours ago
      Verbing weirds language.
  • f311a7 hours ago
    What&#x27;s the current best resources to learn assembly? So that I can understand output of simple functions. I don&#x27;t want to learn to write it properly, I just want to be able to understand on what&#x27;s happening.
    • photochemsyn6 hours ago
      <a href="https:&#x2F;&#x2F;godbolt.org&#x2F;" rel="nofollow">https:&#x2F;&#x2F;godbolt.org&#x2F;</a><p>You can select the assembly output (I like RISCV but you can pick ARM, x86, mips, etc with your choice of compiler) and write your own simple functions. Then put the original function and the assembly output into an LLM prompt window and ask for a line-by-line explanation.<p>Also very useful to get a copy of Computer Organization and Design RISC-V Edition: The Hardware Software Interface, by Patterson and Hennessy.
  • Joker_vD9 hours ago
    Honestly, x86 is not nearly as CISC as those go. It just has a somewhat developed addressing modes comparing to the utterly anemic &quot;register plus constant offset&quot; one, and you are allowed to fold some load-arithmetic-store combinations into a single instruction. But that&#x27;s it, no double- or triple-indexing or anything like what VAXen had.<p><pre><code> BINOP disp(rd1+rd2 shl #N), rs vs. SHL rTMP1, rd2, #N ADD rTMP1, rTMP1, rd1 LOAD rTMP2, disp(rTMP1) BINOP rTMP2, rTMP2, rs STORE disp(rTMP1), rTMP2 </code></pre> And all it really takes to support this is just adding a second (smaller) ALU on your chip to do addressing calculations.
    • jcranmer6 hours ago
      One of my biggest bugbears in CS instruction is the overdue emphasis on RISC v CISC, especially as there aren&#x27;t any really good models to show you what the differences are, given the winnowing of ISAs. In John Mashey&#x27;s infamous posts [1] sort of delineating an ordered list from most RISCy to most CISCy, the architectures that are the most successful have been the ones that really crowded the RISC&#x2F;CISC line--ARM and x86.<p>It also doesn&#x27;t help that, since x86 is the main goto example for CISC, people end up not having a strong grasp on what features of x86 make it actually CISC. A lot of people go straight to its prefix encoding structure or its ModR&#x2F;M encoding structure, but honestly, the latter is pretty much just a &quot;compressed encoding&quot; of RISC-like semantics, and the former is far less insane than most people give it credit for. But x86 <i>does</i> have a few weird, decidedly-CISC instruction semantics in it--these are the string instructions like REP MOVSB. Honestly, take out about a dozen instructions, and you could make a solid argument that modern x86 <i>is</i> a RISC architecture!<p>[1] <a href="https:&#x2F;&#x2F;yarchive.net&#x2F;comp&#x2F;risc_definition.html" rel="nofollow">https:&#x2F;&#x2F;yarchive.net&#x2F;comp&#x2F;risc_definition.html</a>
      • aengelke5 hours ago
        I fully agree, but:<p>&gt; these are the string instructions like REP MOVSB<p>AArch64 nowadays has somewhat similar CPY* and SET* instructions. Does that make AArch64 CISC? :-) (Maybe REP SCASB&#x2F;CMPSB&#x2F;LODSB (the latter being particularly useless) is a better example.)
    • rocqua8 hours ago
      There&#x27;s also a lot of specialized instructions like AES ones.<p>But the main thing that makes x86 CISC to me is not the actual instruction set, but the byte encoding, and the complexity there.
      • 2019847 hours ago
        The classic distinction is that a CISC has data processing instructions with memory operands, and in a RISC they only take register parameters. This gets fuzzy though when you look at AArch64 atomic instructions like ldadd which do read-modify-write all in a single instruction.
      • Joker_vD7 hours ago
        Eh, that&#x27;s really just a side effect of almost 50 years of constant evolution from a 8-bit microprocessor. Take look at VAX [0], for instance: its instruction encoding is pretty clean yet it&#x27;s an actual example of a CISC ISA that was impossible to speed up like, literally: DEC engineers tried very hard and concluded that making a truly pipelined &amp; super-scalar implementation was basically impossible; so DEC had to move to Alpha. See [1] for more from John Mashey.<p>Edit: the very, very compressed TL;DR is that if you do only one memory load (or one memory load + store back into this exact location) per instruction, it scales <i>fine</i>. But the moment you start doing chained loads, with pre- and post-increments which are supposed to write back changed values into the memory and be visible, and you have several memory sources, and your memory model is actually &quot;strong consistency&quot;, well, you&#x27;re in a world of pain.<p>[0] <a href="https:&#x2F;&#x2F;minnie.tuhs.org&#x2F;CompArch&#x2F;Resources&#x2F;webext3.pdf" rel="nofollow">https:&#x2F;&#x2F;minnie.tuhs.org&#x2F;CompArch&#x2F;Resources&#x2F;webext3.pdf</a><p>[1] <a href="https:&#x2F;&#x2F;yarchive.net&#x2F;comp&#x2F;vax.html" rel="nofollow">https:&#x2F;&#x2F;yarchive.net&#x2F;comp&#x2F;vax.html</a>
    • andrepd8 hours ago
      Would this matter for performance? You already have so many execution units that are actually difficult to keep fully fed even when decoding instructions and data at the speed of cache.
      • gpderetta3 hours ago
        Yes. As Joker_vD hints on a sibling comment, this is what killed all the classic CISCs during the OoO transition except for x86 that lacks the more complex addressing modes (and the PPro was still considered a marvel of engineering that was assumed not to be possible).
  • dist-epoch7 hours ago
    Do we really know that LEA is using the hardware memory address computation units? What if the CPU frontend just redirects it to the standard integer add units&#x2F;execution ports? What if the hardware memory address units use those too?<p>It would be weird to have 2 sets of different adders.
    • toast03 hours ago
      &gt; It would be weird to have 2 sets of different adders.<p>Not really. CPUs often have limited address math available separately from the ALU. On simple cores, it looks like a separate incrementer for the Program Counter, on x86 you have a lot of addressing modes that need a little bit of math; having address units for these kinds of things allows more effective pipelining.<p>&gt; Do we really know that LEA is using the hardware memory address computation units?<p>There are ways to confirm. You need an instruction stream that fully loads the ALUs, without fully loading dispatch&#x2F;commit, so that ALU throughput is the limit on your loop; then if you add an LEA into that instruction stream, it shouldn&#x27;t increase the cycle count because you&#x27;re still bottlenecked on ALU throughput and the LEA does address math separately.<p>You <i>might</i> be able to determine if LEAs can be dispatched to the general purpose ALUs if your instruction stream is something like all LEAs... if the throughput is higher than what could be managed with only address units, it must also use ALUs. But you may end up bottlenecked on instruction commit rather than math.
    • adrian_b7 hours ago
      The modern Intel&#x2F;AMD CPUs have distinct ALUs (arithmetic-logic units, where additions and other integer operations are done; usually between 4 ALUs and 8 ALUs in recent CPUs) and AGUs (address generation units, where the complex addressing modes used in load&#x2F;store&#x2F;LEA are computed; usually 3 to 5 AGUs in recent CPUs).<p>Modern CPUs can execute up to between 6 and 10 instructions within a clock cycle, and up to between 3 and 5 of those may be load and store instructions.<p>So they have a set of execution units that allow the concurrent execution of a typical mix of instructions. Because a large fraction of the instructions generate load or store micro-operations, there are dedicated units for address computation, to not interfere with other concurrent operations.
      • dist-epoch7 hours ago
        But can the frontend direct these computations based on what&#x27;s available? If it sees 10 LEA instructions in a row, and it has 5 AGU units, can it dispatch 5 of those LEA instructions to other ALUs?<p>Or is it guaranteed that a LEA instruction will always execute on an AGU, and an ADD instruction always on an ALU?
        • adrian_b6 hours ago
          This can vary from CPU model to CPU model.<p>No recent Intel&#x2F;AMD CPU executes directly LEA or other instructions, they are decoded into 1 or more micro-operations.<p>The LEA instructions are typically decoded into either 1 or 2 micro-operations. The addressing modes that add 3 components are usually decoded into 2 micro-operations, like also the obsolete 16-bit addressing modes.<p>The AGUs probably have some special forwarding paths for the results towards the load&#x2F;store units, which do not exist in ALUs. So it is likely that 1 of the up to 2 LEA micro-operations are executed only in AGUs. On the other hand, when there are 2 micro-operations it is likely that 1 of them can be executed in any ALU. It is also possible for the micro-operations generated by a LEA to be different from those of actual load&#x2F;store instructions, so that they may also be executed in ALUs. This is decided by the CPU designer and it would not be surprising if LEAs are processed differently in various CPU models.
  • secondcoming8 hours ago
    The confusing thing about LEA is that the source operands are within a &#x27;[]&#x27; block which makes it look like a memory access.<p>I&#x27;d love to know why that is.<p>I think the calculation is also done during instruction decode rather than on the ALU, but I could be wrong about that.
    • pwg7 hours ago
      It (LEA) does all the work of a memory access (the address computation part) without actually performing the memory access.<p>Instead of reading from memory at &quot;computed address value&quot; it returns &quot;computed address value&quot; to you to use elsewhere.<p>The intent was likely to compute the address values for MOVS&#x2F;MOVSB&#x2F;MOVSW&#x2F;MOVSD&#x2F;MOVSQ when setting up a REP MOVS (or other repeated string operation). But it turned out they were useful for doing three operand adds as well.
    • trollbridge7 hours ago
      LEA is the equivalent of &amp; in C. It gives you the address of something.<p>Fun question: what does the last line of this do?<p>MOV BP,12 LEA AX,[BP] MOV BX,34 LEA AX,BX
      • hota_mazi7 hours ago
        I think OP was just making a comment on the asymmetry of the syntax. Brackets [] are usually used to dereference.<p>Why is this written<p><pre><code> lea eax, [rdi + rsi] </code></pre> instead of just<p><pre><code> lea eax, rdi + rsi ?</code></pre>
        • sparkie16 minutes ago
          It&#x27;s due to the way the instruction is encoded. `lea` would&#x27;ve needed special treatment in syntax to remove the brackets.<p>In `op reg1, reg2`, the two registers are encoded as 3 bits each the ModRM byte which follows the opcode. Obviously, we can&#x27;t fit 3 registers in the ModRM byte because it&#x27;s only 8-bits.<p>In `op reg1, [reg2 + reg3]`, reg1 is encoded in the ModRM byte. The 3 bits that were previously used for reg2 are instead `0b100`, which indicates a SIB byte follows the ModRM byte. The SIB (Scale-Index-Base) byte uses 3 bits each for reg2 and reg3 as the base and index registers.<p>In any other instruction, the SIB byte is used for addressing, so syntax of `lea` is consistent with the way it is encoded.<p>Encoding details of ModRM&#x2F;SIB are in Volume2, Section 2.1.5 of the ISA manual: <a href="https:&#x2F;&#x2F;www.intel.com&#x2F;content&#x2F;www&#x2F;us&#x2F;en&#x2F;developer&#x2F;articles&#x2F;technical&#x2F;intel-sdm.html" rel="nofollow">https:&#x2F;&#x2F;www.intel.com&#x2F;content&#x2F;www&#x2F;us&#x2F;en&#x2F;developer&#x2F;articles&#x2F;t...</a>
        • jcranmer6 hours ago
          When you encode an x86 instruction, your operands amount to either a register name, a memory operand, or an immediate (of several slightly different flavors). I&#x27;m no great connoisseur of ISAs, but I believe this basic trichotomy is fairly universal for ISAs. The operands of an LEA instruction are the destination register and a memory operand [1]. LEA happens to be the unique instruction where the memory operand is not dereferenced in some fashion in the course of execution; it doesn&#x27;t make a lot of sense to create an entirely new syntax that works only for a single instruction.<p>[1] On a hardware level, the ModR&#x2F;M encoding of most x86 instructions allows you to specify a register operand and either a memory or a register operand. The LEA instruction only allows a register and a memory operand to be specified; if you try to use a register and register operand, it is instead decoded as an illegal instruction.
          • aengelke5 hours ago
            &gt; LEA happens to be the unique instruction where the memory operand is not dereferenced<p>Not quite unique: the now-deprecated Intel MPX instructions had similar semantics, e.g. BNDCU or BNDMK. BNDLDX&#x2F;BNDSTX are even weirder as they don&#x27;t compute the address as specified but treat the index part of the memory operand separately.
        • Y_Y6 hours ago
          The way I rationalize it is that you&#x27;re getting the address of something. A raw address isn&#x27;t what you want the address of, so you&#x27;re doing something like &amp;(*(rdi+rsi)).
        • secondcoming6 hours ago
          Yes, that’s what I meant
          • HarHarVeryFunny6 hours ago
            LEA stands for Load Effective Address, so the syntax is as-if you&#x27;re doing a memory access, but you are just getting the calculated address, not reading or writing to that address.<p>LEA would normally be used for things like calculating address of an array element, or doing pointer math.
  • tony-john127 hours ago
    [dead]