18 comments

  • Suzuran 1 hour ago
    On some of IBM's smaller processors, such as channel controllers and the CSP used in the midrange line prior to the System/38, the xor instruction had a special feature when used with identical source and destination - It would inhibit parity and/or ECC error checking on the read cycle, which meant that xor could be used to clear a register or memory location that had been stored with bad parity without taking a machine check or processor check.
  • Sweepi 6 hours ago
    "Bonus bonus chatter: The xor trick doesn’t work for Itanium because mathematical operations don’t reset the NaT bit. Fortunately, Itanium also has a dedicated zero register, so you don’t need this trick. You can just move zero into your desired destination."

    Will remember for the next time I write asm for Itanium!

    • shawn_w 6 hours ago
      Quite a few architectures have a dedicated 0 register.
      • repelsteeltje 5 hours ago
        Yep. The XOR trick - relying on special use of opcode rather than special register - is probably related to limited number of (general purpose) registers in typical '70 era CPU design (8080, 6502, Z80, 8086).
        • classichasclass 1 hour ago
          Unfortunately, 6502 can't XOR the accumulator with itself. I don't recall if the Z80 can, and loading an immediate 0 would be most efficient on those anyway.
          • blywi 43 minutes ago
            XOR A absolutely works on Z80 and it's of course faster and shorter than loading a zero value with LD A,0. LD A,0 is encoded to 2 bytes while XOR A is encoded as a single opcode. XOR A has the additional benefit to also clear all the flags to 0. Sub A will clear the accumulator, but it will always set the N flag on Z80.
          • bonzini 45 minutes ago
            The Z80 can do either LD A,0 or SUB A or XOR A, but the LD is slower due to the extra memory cycle to load the second byte of the instruction.
        • wongarsu 45 minutes ago
          And [as mentioned in the article] even modern x86 implementations have a zero register. So you have this weird special opcode that (when called with identical source and destination) only triggers register renaming
        • bonzini 1 hour ago
          A move on SPARC is technically an OR of the source with the zero register. "move %l0, %l1" is assembled as "or %g0, %l0, %l1". So if you want to zero a register you OR %g0 with itself.
      • lynguist 5 hours ago
        Indeed!!

        MIPS - $zero

        RISC-V - x0

        SPARC - %g0

        ARM64 - XZR

        • classichasclass 1 hour ago
          PowerPC: "r0 occasionally" (with certain instructions like addi, though this might be better considered an edge case of encoding)
      • signa11 5 hours ago
        indeed. riscv for instance. also, afaik, xor’ing is faster. i would assume that someone like mr. raymond would know…
        • pif 5 hours ago
          Which part of "mathematical operations don’t reset the NaT bit" did you not understand?
        • IshKebab 5 hours ago
          > afaik, xor’ing is faster

          Even tiny tiny CPUs can do sub in one cycle, so I doubt that. On super-scalar CPUs xor and sub are normally issued to the same execution units so it wouldn't make a difference there either.

          • tliltocatl 5 hours ago
            On superscalars running xor trick as is would be significantly slower because it implies a data dependency where there isn't one. But all OOO x86's optimize it away internally.
  • NewCzech 6 hours ago
    The obvious answer is that XOR is faster. To do a subtract, you have to propagate the carry bit from the least-significant bit to the most-significant bit. In XOR you don't have to do that because the output of every bit is independent of the other adjacent bits.

    Probably, there are ALU pipeline designs where you don't pay an explicit penalty. But not all, and so XOR is faster.

    Surely, someone as awesome as Raymond Chen knows that. The answer is so obvious and basic I must be missing something myself?

    • Someone 25 minutes ago
      > To do a subtract, you have to propagate the carry bit from the least-significant bit to the most-significant bit.

      Yes, but that need not scale linearly with the number of bits. https://en.wikipedia.org/wiki/Carry-lookahead_adder:

      “A carry-lookahead adder (CLA) or fast adder is a type of electronics adder used in digital logic. A carry-lookahead adder […] can be contrasted with the simpler, but usually slower, ripple-carry adder (RCA), for which the carry bit is calculated alongside the sum bit, and each stage must wait until the previous carry bit has been calculated to begin calculating its own sum bit and carry bit. The carry-lookahead adder calculates one or more carry bits before the sum, which reduces the wait time to calculate the result of the larger-value bits of the adder.

      […]

      Already in the mid-1800s, Charles Babbage recognized the performance penalty imposed by the ripple-carry used in his difference engine, and subsequently designed mechanisms for anticipating carriage for his never-built analytical engine.[1][2] Konrad Zuse is thought to have implemented the first carry-lookahead adder in his 1930s binary mechanical computer, the Zuse Z1.”

      I think most, if not all, current ALUs implement such adders.

      • dreamcompiler 10 minutes ago
        Carry lookahead is definitely faster than ripple carry but it's not free. It requires high-fan-in gates that take up a fair amount of silicon. That silicon saves time though, so as you say almost nobody uses ripple carry any more.
    • svnt 6 hours ago
      His point is that in x86 there is no performance difference but everyone except his colleague/friend uses xor, while sub actually leaves cleaner flags behind. So he suspects its some kind of social convention selected at random and then propagated via spurious arguments in support (or that it “looks cooler” as a bit of a term of art).

      It could also be as a result of most people working in assembly being aware of the properties of logic gates, so they carry the understanding that under the hood it might somehow be better.

      • zahlman 1 hour ago
        GP seems to think it strange that "x86" would actually not have a performance difference here.

        I think this might just be due to not realizing just how far back in CPU history this goes.

        • wongarsu 35 minutes ago
          In a clockless cpu design you'd indeed expect xor to be faster. But in a regular CPU with a clock you either waste a bit of xor performance by making xor and sub both take the same number of ticks, or you speed up the clock enough that the speed difference between xor and sub justifies sub being at least a full tick slower

          The former just seems way more practical

          • dbdr 9 minutes ago
            Even if they take the same number of ticks, shouldn't xor fundamentally needing less work also mean it can be performed while drawing less power/heating less, which is just as much an improvement in the long run?
      • 3form 6 hours ago
        I think an even more likely explanation would be that x86 assembly programmers often were, or learned from other-architecture assembly programmers. Maybe there's a place where it makes more sense and it can be so attributed. 6502 and 68k being first places I would look at.
        • bonzini 1 hour ago
          6502 doesn't even have register-to-register ALU operations, there's no alternative to LDA #0.

          8080/Z80 is probably where XOR A got a lead over SUB A, but they are also the same number of cycles.

        • richrichardsson 5 hours ago
          For 68k depending on the size you're interested in then it mostly doesn't matter.

          .b and .w -> clr eor sub are all identical

          for .l moveq #0 is the winner

    • arka2147483647 6 hours ago
      > The answer is so obvious

      A tangent, but what is Obvious depends on what you know.

      Often experts don't explain the things they think are Obvious, but those things are only Obvious to them, because they are the expert.

      We should all kind, and explain also the Obvious things those who do not know.

      • akie 6 hours ago
        "The proof is left as an exercise for the reader" comes to mind
    • flohofwoe 6 hours ago
      That comment is not very useful without pointing to realworld CPUs where SUB is more expensive than XOR ;)

      E.g. on Z80 and 6502 both have the same cycle count.

      • em3rgent0rdr 13 minutes ago
        With more bits, then SUB is going to be more and more expensive to fit in the same number of clocks as XOR. So with an 8-bit CPU like Z80, it probably makes design sense to have XOR and SUB both take one cycle. But if for instance a CPU uses 128-bit registers, then the propagate-and-carry logic for ADD/SUB might take way much longer than XOR that the designers might not try to fit ADD/SUB into the same single clock cycle as XOR, and so might instead do multi-cycle pipelined ADD/SUB.

        A real-world CPU example is the Cray-1, where S-Register Scalar Operations (64-bit) take 3 cycles for ADD/SUB but still only 1 cycle for XOR. [1]

        [1] https://ed-thelen.org/comp-hist/CRAY-1-HardRefMan/CRAY-1-HRM...

      • HarHarVeryFunny 2 hours ago
        The 6502 doesn't support XOR A or SUB A, and in fact doesn't have a SUB opcode at all, only SBC (subtract with carry, requiring an extra opcode to set the carry flag beforehand).
        • flohofwoe 59 minutes ago
          I was handwaving over the details, SBC is identical to SUB when the carry flag is clear, so it's understandable why the 6502 designers didn't waste an instruction slot.

          EOR and SBC still have the same cycle counts though.

      • brigade 5 hours ago
        Cortex A8 vsub reads the second source register a cycle earlier than veor, so that can add one cycle latency

        Not scalar, but still sub vs xor. Though you’d use vmov immediate for zeroing anyway.

      • GoblinSlayer 4 hours ago
        Harvard Mark I? Not sure why people think programming started with Z80.
        • bonzini 58 minutes ago
          The article is about x86, and x86 assembly is mostly a superset of 8080 (which is why machine language numbers registers as AX/CX/DX/BX, matching roughly the function of A/BC/DE/HL on the 8080—in particular with respect to BX and HL being last).
        • flohofwoe 1 hour ago
          My WW2-era assembly is a bit rusty, but I don't think the Harvard Mark 1 had bitwise logical operations?
    • phire 6 hours ago
      I'm not actually aware of any CPUs that preform a XOR faster than a SUB. And more importantly, they have identical timings on the 8086, which is where this pattern comes from.
      • HarHarVeryFunny 38 minutes ago
        The XOR A,A trick goes at least back to the IBM System/360 back in 1964, and in the microprocessor world to the 8008.

        According to Claude on the IBM 360 SUB A,A was actually the preferred way since that's what IBM programmers were familiar with (earlier IBM mainframes didn't support XOR), it's more readable, and XOR A,A offered no advantage.

    • drob518 1 hour ago
      Yea, that’s what immediately went through my head, too. XOR is ALWAYS going to be single cycle because it’s bit-parallel.
    • billpg 6 hours ago
      I had a similar reaction when learning 8086 assembly and finding the correct way to do `if x==y` was a CMP instruction which performed a subtraction and set only the flags. (The book had a section with all the branch instructions to use for a variety of comparison operators.) I think I spent a few minutes experimenting with XOR to see if I could fashion a compare-two-values-and-branch macro that avoided any subtraction.
    • mikequinlan 6 hours ago
      As TFA says, on x86 `sub eax, eax` encodes to the same number of bytes and executes in the same number of cycles.
      • whizzter 5 hours ago
        On modern ones, x86 has quite a history and the idiom might carry on from an even older machine.

        Edit: Looked at comments, seems like x86 and the major 8bit cpu's had the same speed, pondering in this might be a remnant from the 4-bit ALU times.

        • abainbridge 4 hours ago
          > seems like x86 and the major 8bit cpu's had the same speed, pondering in this might be a remnant from the 4-bit ALU times.

          I think that era of CPUs used a single circuit capable of doing add, sub, xor etc. They'd have 8 of them and the signals propagate through them in a row. I think this page explains the situation on the 6502: https://c74project.com/card-b-alu-cu/

          And this one for the ARM 1: https://daveshacks.blogspot.com/2015/12/inside-alu-of-armv1-...

          But I'm a software engineer speculating about how hardware works. You might want to ask a hardware engineer instead.

        • adrian_b 3 hours ago
          Nope.

          In any ALU the speed is determined by the slowest operation, so XOR is never faster. It does not matter which is the width of the ALU, all that matters is that an ALU does many kinds of operations, including XOR and subtraction, where the operation done by an ALU is selected by some control bits.

          I have explained in another comment that the only CPUs where XOR can be faster than subtraction are the so-called superpipelined CPUs. Superpipelined CPUs have been made only after 1990 and there were very few such CPUs. Even if in superpipelined CPUs it is possible for XOR to be faster than subtraction, it is very unlikely that this feature has been implemented in anyone of the few superpipelined CPU models that have ever been made, because it would not have been worthwhile.

          For general-purpose computers, there have never been "4-bit ALU times".

          The first monolithic general-purpose processor was Intel 8008 (i.e. the monolithic version of Datapoint 2200), with an 8-bit ISA.

          Intel claims that Intel 4004 was the first "microprocessor" (in order to move its priority earlier by one year), but that was not a processor for a general-purpose computer, but a calculator IC. Its only historical relevance for the history of personal computers is that the Intel team which designed 4004 gained a lot of experience with it and they established a logic design methodology with PMOS transistors, which they used for designing the Intel 8008 processor.

          Intel 4004, its successors and similar 4-bit processors introduced later by Rockwell, TI and others, were suitable only for calculators or for industrial controllers, never for general-purpose computers.

          The first computers with monolithic processors, a.k.a. microcomputers, used 8-bit processors, and then 16-bit processors, and so on.

          For cost reduction, it is possible for an 8-bit ISA to use a 4-bit ALU or even just a serial 1-bit ALU, but this is transparent for the programmer and for general-purpose computers there never were 4-bit instruction sets.

    • Tepix 6 hours ago
      From TFA:

      > It encodes to the same number of bytes, executes in the same number of cycles.

      • abainbridge 4 hours ago
        Those aren't the only resources. I could imagine XOR takes less energy because using it might activate less circuitry than SUB.
        • zahlman 1 hour ago
          I'm not aware of any stories in the historical record of "real programmers" optimizing for power use, only for speed or code size.
    • bialpio 3 hours ago
      From TFA:

      The predominance of these idioms as a way to zero out a register led Intel to add special xor r, r-detection and sub r, r-detection in the instruction decoding front-end and rename the destination to an internal zero register, bypassing the execution of the instruction entirely.

    • adrian_b 3 hours ago
      XOR is faster when you do that alone in an FPGA or in an ASIC.

      When you do XOR together with many other operations in an ALU (arithmetic-logical unit), the speed is determined by the slowest operation, so the speed of any faster operation does not matter.

      This means that in almost all CPUs XOR and addition and subtraction have the same speed, despite the fact that XOR could be done faster.

      In a modern pipelined CPU, the clock frequency is normally chosen so that a 64-bit addition can be done in 1 clock cycle, when including all the overheads caused by registers, multiplexers and other circuitry outside the ALU stages.

      Operations more complex than 64-bit addition/subtraction have a latency greater than 1 clock cycle, even if one such operation can be initiated every clock cycle in one of the execution pipelines.

      The operations less complex than 64-bit addition/subtraction, like XOR, are still executed in 1 clock cycle, so they do not have any speed advantage.

      There have existed so-called superpipelined CPUs, where the clock frequency is increased, so that even addition/subtraction has a latency of 2 or more clock cycles.

      Only in superpipelined CPUs it would be possible to have a XOR instruction that is faster than subtraction, but I do not know if this has ever been implemented in a real superpipelined CPU, because it could complicate the execution pipeline for negligible performance improvements.

      Initially superpipelining was promoted by DEC as a supposedly better alternative to the superscalar processors promoted by IBM. However, later superpipelining was abandoned, because the superscalar approach provides better energy efficiency for the same performance. (I.e. even if for a few years it was thought that a Speed Demon beats a Brainiac, eventually it was proven that a Brainiac beats a Speed Demon, like shown in the Apple CPUs)

      While mainstream CPUs do not use superpipelining, there have been some relatively recent IBM POWER CPUs that were superpipelined, but for a different reason than originally proposed. Those POWER CPUs were intended for having good performance only in multi-threaded workloads when using SMT, and not in single-thread applications. So by running simultaneous threads on the same ALU the multi-cycle latency of addition/subtraction was masked. This technique allowed IBM a simpler implementation of a CPU intended to run at 5 GHz or more, by degrading only the single-thread performance, without affecting the SMT performance. Because this would not have provided any advantage when using SMT, I assume that in those POWER CPUs XOR was not made faster than subtraction, even if this would have theoretically been possible.

    • virexene 6 hours ago
      The operation is slightly more complex yes, but has there ever been an x86 CPU where SUB or XOR takes more than a single CPU cycle?
      • praptak 6 hours ago
        I wonder if you could measure the difference in power consumption.

        I mean, not for zeroing because we know from the TFA that it's special-cased anyway. But maybe if you test on different registers?

    • defmacr0 5 hours ago
      I would be surprised if modern CPUs didn't decode "xor eax, eax" into a set of micro-ops that simply moves from an externally invisible dedicated 0 register. These days the x86 ISA is more of an API contract than an actual representation of what the hardware internals do.
      • defrost 5 hours ago
        From TFA:

          The predominance of these idioms as a way to zero out a register led Intel to add special xor r, r-detection and sub r, r-detection in the instruction decoding front-end and rename the destination to an internal zero register, bypassing the execution of the instruction entirely. You can imagine that the instruction, in some sense, “takes zero cycles to execute”.
        • rasz 2 hours ago
          "rename the destination to an internal zero register"

          That would be quite late then, 1997 Pentium 2 for general population.

      • brigade 5 hours ago
        Zero micro ops to be precise, that’s handled entirely at the register rename stage with no data movement.
    • feverzsj 6 hours ago
      It's like 0.5 cycles vs 0.9 cycles. So both are 1 cycle, considering synchronization.
      • pishpash 6 hours ago
        But energy consumption could be different for this hypothetical 0.5 and 0.9.
        • scheme271 5 hours ago
          Energy consumption wasn't really a concern when the idiom developed. I don't think people really cared about the energy consumption of instructions until well into the x86-64 era.
          • allenrb 1 hour ago
            Not sure why this is being downvoted, but it’s absolutely correct. For most of the history of computing, people were happy that it worked at all. Being concerned about energy efficiency is a recent byproduct of mobile devices and, even more recently, giant amounts of compute adding up to gigawatts.
    • jojobas 6 hours ago
      The non-obvious bit is why there isn't an even faster and shorter "mov <register>,0" instructions - the processors started short-circuiting xor <register>,<register> much later.
      • defmacr0 19 minutes ago
        In x86, a basic immediate instruction with a 1 Byte immediate value is encoded like this:

        <op> (1 Byte opcode), <Registers> (1 Byte), <immediate value> (1 Byte)

        While xor eax, eax only uses 2 bytes. Since there are only 8 registers, meaning they can be encoded with 3 bits, you can pack two values into the <Registers> field (ModR/M).

        Making mov eax, 0 only take two bytes would require significant changes of the ISA to allow immediate values in the ModR/M byte (or similar) but there would be little benefit since zeroing can already be done in 2 bytes and I doubt that other cases are even close to frequent enough for this to be any significant benefit overall. An actual improvement would be if there was a dedicated 1 Byte set-rax-to-0 instruction, but obviously that comes at a tradeoff where we have to encode another operation differently (probably with more bytes) again (and you can't zero anything else with it).

        https://wiki.osdev.org/X86-64_Instruction_Encoding

        https://pyokagan.name/blog/2019-09-20-x86encoding/

      • HarHarVeryFunny 22 minutes ago
        A number of the RISC processors have a special zero register, giving you a "mov reg, zero" instruction.

        Of course many of the RISC processors also have fixed length instructions, with small literal values being encoded as part of the instruction, so "mov reg, #0" and "mov reg, zero" would both be same length.

      • drob518 1 hour ago
        Right, like a “set reg to zero” instruction. One byte. Just encodes the operation and the reg to zero. I’m surprised we didn’t have it on those old processors. Maybe the thinking was that it was already there: xor reg,reg.
        • bonzini 53 minutes ago
          One byte instructions, with 8 registers as in the 8086, waste 8 opcodes which is 3% of the total. There are just five: "INC reg", "DEC reg", "PUSH reg", "POP reg", "XCHG AX, reg" (which is 7 wasted opcodes instead of 8, because "XCHG AX, AX" doubles as NOP).

          One-byte INC/DEC was dropped with x86-64, and PUSH/POP are almost obsolete in APX due to its addition of PUSH2/POP2, leaving only the least useful of the five in the most recent incantation of the instruction set.

          • drob518 44 minutes ago
            I’m not sure I understand what you mean by “waste 8 opcodes.”
            • LegionMammal978 6 minutes ago
              Traditionally in x86, only the first byte is the opcode used to select the instruction, and any further bytes contain only operands. Thus, since there exist 256 possible values for the initial byte, there are at most 256 possible opcodes to represent different instructions.

              So if you add a 1-byte instruction for each register to zero its value, that consumes 8 of the possible 256 opcodes, since there are 8 registers. Traditional x86 did have several groups of 1-byte instructions for common operations, but most of them were later replaced with multibyte encodings to free up space for other instructions.

            • bonzini 12 minutes ago
              They occupy 8 of the possible 256 byte values. Together, those five cases used about 15% of the space.

              Though I was forgetting one important case: MOV r,imm also used one-byte opcodes with the register index embedded. And it came in byte and word variants, so it used a further 16 opcodes bytes for a total of 56 one byte opcodes with register encoding.

        • flohofwoe 51 minutes ago
          Instruction slots are extremely valuable in 8-bit instruction sets. The Z80 has some free slots left in the ED-prefixed instruction subset, but being prefix-instructions means they could at best run at half speed of one-byte instructions (8 vs 4 clock cycles).
    • TacticalCoder 3 hours ago
      > The obvious answer is that XOR is faster.

      It used to be not only faster but also smaller. And back then this mattered.

      Say you had a computer running at 33 Mhz, you had 33 million cycles per second to do your stuff. A 60 Hz game? 33 million / 60 and suddenly you only have about 500 000 cycles per frame. 200 scanlines? Suddenly you're left with only 2500 cycles per scanline to do your stuff. And 2500 cycles really isn't that much.

      So every cycle counted back then. We'd use the official doc and see how many cycles each instruction would take. And we'd then verify by code that this was correct too. And memory mattered too.

      XOR was both faster and smaller (less bytes) then a MOV ..., 0.

      Full stop.

      And when those CPU first began having cache, the cache were really tiny at first: literally caching ridiculously low number of CPU instructions. We could actually count the size of the cache manually (for example by filling with a few NOP instructions then modifying them to, say, add one, and checking which result we got at the end).

      XOR, due to being smaller, allowed to put more instructions in the cache too.

      Now people may lament that it persisted way long after our x86 CPUs weren't even real x86 CPUs anymore and that is another topic.

      But there's a reason XOR was used and people should deal with it.

      We zero with XOR EAX,EAX and that's it.

      • zahlman 1 hour ago
        The context was comparison to SUB EAX,EAX, not to a MOV.
    • bahmboo 5 hours ago
      Because he is explicitly talking about x86 - maybe you missed that.
    • themafia 6 hours ago
      XOR and SUB have had identical cycle counts and latencies since the 8088. That's because you can "look ahead" when doing carries in binary. It's just a matter of how much floorspace on the chip you want to use.

      https://en.wikipedia.org/wiki/Carry-lookahead_adder

      The only minor difference between the two on x86, really, is SUB sets OF and CF according to the result while XOR always clears them.

      • bonzini 52 minutes ago
        OF/CF/AF are always cleared anyway by SUB r,r. So there's absolutely no difference.
      • asQuirreL 5 hours ago
        A carry lookahead adder makes your circuit depth logarithmic in the width of the inputs vs linear for a ripple carry adder, but that is still asymptotically worse than XORs constant depth.

        (But this does not discount the fact that basically all CPUs treat them both as one cycle)

  • b1temy 5 hours ago
    Back when I was in university, one of the units touching Assembly[0] required students to use subtraction to zero out the register instead of using the move instruction (which also worked), as it used fewer cycles.

    I looked it up afterwards and xor was also a valid instruction in that architecture to zero out a register, and used even fewer cycles than the subtraction method; but it was not listed in the subset of the assembly language instructions we were allowed to use for that unit. I suspect that it was deemed a bit off-topic, since you would need to explain what the mathematical XOR operation was (if you didn't already learn about it in other units), when the unit was about something else entirely- but everyone knows what subtraction is, and that subtracting a number by itself leads to zero.

    [0] Not x86, I do not recall the exact architecture.

  • drfuchs 5 hours ago
    Relatedly, there's a steganographic opportunity to hide info in machine code by using "XOR rax,rax" for a "zero" and "SUB rax,rax" for a "one" in your executable. Shouldn't be too hard to add a compiler feature to allow you to specify the string you want encoded into its output.
    • gynvael 1 hour ago
      This sounds like a Paged Out article ;)
  • nopurpose 6 hours ago
    It amazes me how entertaining Raymond's writing on most mundane aspects of computing often is.
  • zahlman 1 hour ago
    > but xor took a slightly lead due to some fluke, perhaps because it felt more “clever”.

    Absolutely. But I can also imagine that it feels more like something that should be more efficient, because it's "a bit hack" rather than arithmetic. After all, it avoids all the "data dependencies" (carries, never mind the ALU is clocked to allow time for that regardless)!

    I imagine that a similar feeling is behind XOR swap.

    > Once an instruction has an edge, even if only extremely slight, that’s enough to tip the scales and rally everyone to that side.

    Network effects are much older than social media, then....

  • enduku 5 hours ago
    I ran into this rabbithole while writing an x86-64 asm rewriter.

    xor was the default zeroing idiom.I onkly did sub reg,reg when I actually want its flags result. Otherwise the main rule is: do not touch either form unless flags liveness makes the rewrite obviously safe. Had about 40 such idioms for the passes.

  • dreamcompiler 23 minutes ago
    I vaguely remember we used the XOR trick on processors other than Intel, so it may not be Intel-specific.

    In principle, sub requires 4 steps:

    1. Move both operands to the ALU

    2. Invert second operand (twos complement convert)

    3. Add (which internally is just XOR plus carry propagate)

    4. Move result to proper result register.

    This is absolutely not how modern processors do it in practice; there are many shortcuts, but at least with pure XOR you don't need twos complement conversion or carry propagation.

    Source: Wrote microcode at work a million years ago when designing a GPU.

  • adrian_b 4 hours ago
    It should be noted that XOR is just (bitwise) subtraction modulo 2.

    There are many kinds of SUB instructions in the x86-64 ISA, which do subtraction modulo 2^64, modulo 2^32, modulo 2^16 or modulo 2^8.

    To produce a null result, any kind of subtraction can be used, and XOR is just a particular case of subtraction, it is not a different kind of operation.

    Unlike for bigger moduli, when operations are done modulo 2 addition and subtraction are the same, so XOR can be used for either addition modulo 2 or subtraction modulo 2.

    • gblargg 1 hour ago
      > XOR is just a particular case of subtraction, it is not a different kind of operation.

      It's different in that there's no carry propagation.

  • defrost 6 hours ago

      Once an instruction has an edge, even if only extremely slight, that’s enough to tip the scales and rally everyone to that side.
    
    And this, interestingly, is why life on earth uses left-handed amino acids and right-handed sugars .. and why left handed sugar is perfect for diet sodas.
    • JuniperMesos 5 hours ago
      This is a hypothesis about why the chirality of life on earth is what it is, but I don't think there's enough evidence to state that this (or any competing hypothesis) is definitely the correct explanation.
      • defrost 5 hours ago
        Well "definitely correct" has no real place in probabilistic arguments almost by ipso factum absurdum :-)

        The chirality argument made is more akin to dynamic systems balance; yes, you can balance a pencil on its point .. but given a bit of random tilt one way or the other it's going to tend to keep going and end near flat on the table.

    • praptak 5 hours ago
      You still need to explain why this case creates a positive feedback loop rather than a negative one. I mean left/right fuel intakes in cars and male/female ratios somehow tend to balance at 50/50.
      • ben_w 4 hours ago
        Regarding gender ratios: https://en.wikipedia.org/wiki/Fisher's_principle

        There's exceptions, but they tend to be colonial animals in the broadest sense e.g. how clownfish males are famously able to become female but each group has one breeding male and one breeding female at any given time*, or bees where the males (drones) are functionally flying sperm and there's only one fertile female in any given colony; or some reptiles which have a temperature-dependent sex determination that may have been 50/50 before we started causing rapid climate change but in many cases isn't now: https://en.wikipedia.org/wiki/Temperature-dependent_sex_dete...

        * Wolves, despite being where nomenclature of "alpha" comes from, are not this. The researcher who coined the term realised they made a mistake and what he thought of as the "alpha" pair were simply the parents of the others in that specific situation: https://davemech.org/wolf-news-and-information/

      • phenol 5 hours ago
        products of an asymmetric reaction performed without enantiomeric control can selectively catalyse the formation of more products with the same handedness -- this is called autocatalysis. so the first full reaction might produce a left-handed product (by chance) but that left-handed product will then cause future products to be preferentially left-handed. see the [Soai reaction](https://en.wikipedia.org/wiki/Soai_reaction?wprov=sfla1) for an example of this.

        as mentioned by others this is conjectural but it is a popular (if somewhat unfalsifiable) explanation for homochirality

      • defrost 5 hours ago
        Wrt amino acids and sugars I personally don't have to explain as a good many others have already.

        eg: For one, Isaac Asimov in the 1970s wrote at length on this in his role as a non fiction science writer with a Chemistry Phd

        > male/female ratios somehow tend to balance at 50/50.

        This is different to the case of actual right handed dominance in humans and to L- Vs R- dominance in chirality ...

        ( Men and women aren't actual mirror images of each other ... )

      • tbrownaw 1 hour ago
        > left/right fuel intakes in cars

        Are I believe chosen by intelligent humans who are deliberately trying to keep the lines at gas stations balanced.

  • tliltocatl 6 hours ago
    It might be because XOR is rarely (in terms of static count, dynamically it surely appears a lot in some hot loops) used for anything else, so it is easier to spot and identify as "special" if you are writing manual assembly.
    • stingraycharles 6 hours ago
      And helps with SMT

      Edit: this is apparently not the case, see @tliltocatl's comment down the thread

      • tliltocatl 6 hours ago
        What's SMT in this context?
        • recursivecaveat 5 hours ago
          Simultaneous Multi-Threading (hyper-threading as Intel calls it). I'm not a cpu guy, but I think the ALU used for subtraction would be a more valuable resource to leave available to the other thread than whatever implements a xor. Hence you prefer to use the xor for zeroing and conserve the ALU for other threads to use.
          • tliltocatl 5 hours ago
            I don't think that's how it works.

            - Normally ALU implements all "light" operations (i. e. add/sub/and/or/xor) in a single block, separating them would result in far more interconnect overhead. Often, CPUs have specialized adder-only units for address generation, but never a xor-specialized block.

            - All CPUs that implement hyper-threading also optimize a XOR EAX,EAX into MOV EAX,ZERO/SET FLAGS (where ZERO is an invisible zero register just like on Itanium and RISCs). This helps register renaming and eliminates a spurious dependency.

            - The XOR trick is about as old as 8086 if not older.

          • fredoralive 5 hours ago
            By the time you get to a CPU complex enough to be to have SMT it is likely to detect these “clear register” patterns and special case them.

            XOR would also be handled by the ALU, the L is for logic.

          • IshKebab 4 hours ago
            Most CPU use the same ALU for xor and sub.
    • kunley 5 hours ago
      XOR appears a lot in any code touching encryption.

      PS. What is static vs dynamic count?

      • tliltocatl 5 hours ago
        Static count - how many times an instruction appears in a binary (or assembly source).

        Dynamic count - how many times an opcode gets executed.

        I. e. an instruction that doesn't appear often in code, but comes up in some hot loops (like encryption) would have low static and high dynamic.

  • empiricus 6 hours ago
    The hw implementation of xor is simpler than sub, so it should consume slightly less energy. Wondering how much energy was saved in the whole world by using xor instead of sub.
  • anematode 6 hours ago
    My favorite (admittedly not super useful) trick in this domain is that sbb eax, eax breaks the dependency on the previous value of eax (just like xor and sub) and only depends on the carry flag. arm64 is less obtuse and just gives you csetm (special case of csinv) for this purpose.
  • jhoechtl 6 hours ago
    Back in the stone ages XOR ing was just 1 byte of opcode. Habbits stick. In effect XORing is no longer faster since a long time.
    • dragontamer 5 hours ago
      The XOR trick is implemented as a (malloc from register file) on modern processors, implemented in the decoder and it won't even issue a uOp to the execution pipelines.

      Its basically free today. Of course, mov RAX, 0 is also free and does the same thing. But CPUs have limited decoder lengths per clock tick, so the more instructions you fit in a given size, the more parallel a modern CPU can potentially execute.

      So.... definitely still use XOR trick today. But really, let the compiler handle it. Its pretty good at keeping track of these things in practice.

      -----------

      I'm not sure if "sub" is hard-coded to be recognized in the decoder as a zero'd out allocation from the register file. There's only certain instructions that have been guaranteed to do this by Intel/AMD.

    • flohofwoe 5 hours ago
      Depending on what's stone-age for you, a SUB with a register was also only one byte, and was the same cost as XOR, at least in the Intel/Zilog lineage all the way back to the 70s ;)
  • rasz 6 hours ago
    Looking at some random 1989 Zenith 386SX bios written in assembly so purely programmer preferences:

    8 'sub al, al', 14 'sub ah, ah', 3 'sub ax, ax'

    26 'xor al, al', 43 'xor ah, ah', 3 'xor ax, ax'

    edit: checked a 2010 bios and not a single 'sub x, x'

    • pishpash 5 hours ago
      Could be used to express 1 bit of information in some non-obvious convention.
  • jdw64 5 hours ago
    [dead]
  • grebc 6 hours ago
    [flagged]