5 ms·
The instruction `repne scasb`[1] stood out. `repne X` means "while (not equal) { X; }". How is `repne` implemented? Is `repne scasb` assembly shorthand for a `s
by jamesfisher 10y ago
The instruction `repne scasb`[1] stood out. `repne X` means "while (not equal) { X; }". How is `repne` implemented? Is `repne scasb` assembly shorthand for a `scasb` then a `jne`? Or is `repne` some fancy higher-order instruction which takes another instruction as its argument?
[1]: https://github.com/kelseyhightower/echo/blob/53d84ea4e79db3dbe27688b5d45d839854851a57/echo.asm#L32 https://github.com/kelseyhightower/echo/blob/53d84ea4e79db3d...
- Stratoscope 10y agoThe latter. The various REPxx prefixes cause a string instruction like SCASB to be repeated until some condition is satisfied. These date back all the way to the 8086/8088. They were the fastest way to do string operations on those early CPUs, but I don't think this the case on modern CPUs. https://www.google.com/search?q=intel+rep+prefix https://www.google.com/search?q=intel+rep+prefix http://wiki.osdev.org/X86-64_Instruction_Encoding#REPNE.2FREPNZ.2C_REP_and_REPE.2FREPZ_prefixes http://wiki.osdev.org/X86-64_Instruction_Encoding#REPNE.2FRE... https://courses.engr.illinois.edu/ece390/archive/spr2002/books/labmanual/inst-ref-scasb.html https://courses.engr.illinois.edu/ece390/archive/spr2002/boo...
- tptacek 10y agoThey're still the x86-64 implementation for things like strlen on a bunch of platforms. They're not always the fastest, but have code size advantages. http://agner.org/optimize/optimizing_assembly.pdf http://agner.org/optimize/optimizing_assembly.pdf
- Stratoscope 10y agoThat's a really interesting document - I am going to spend some time studying it, thanks! Good point about the code size. I imagine there are likely to be cases where that would let some algorithm run faster overall because it fits in the instruction cache, even if the string operation considered on its own is slower.
- pvitz 10y agoI also remember them being called "software machine gun" by Duntemann in his assembly book. Using REP STOSW could save you 5 instructions.
- exDM69 10y ago> They were the fastest way to do string operations on those early CPUs, but I don't think this the case on modern CPUs. Modern CPUs still have a fast path for string operations, and I recall hearing that they even had some improvements not too long ago (in Sandy Bridge or other recent arch). CPUs may be smart enough to detect a memcpy done with a loop, but REPxx is the preferred way - even on modern CPUs.
- userbinator 10y agoHow is `repne` implemented? It's a microcode loop. Here is the appropriate pseudocode (this is extracted from the Intel manuals): http://qcd.phys.cmu.edu/QCDcluster/intel/vtune/reference/vc276.htm http://qcd.phys.cmu.edu/QCDcluster/intel/vtune/reference/vc2...