NaN memories

March 12, 2015 – 6:02 am

A nice thing about Twitter is that single tweet can bring so many memories. It all started when Fiora posted this. It reminded me of an old bug I encountered few years ago when working on a multi-platform (PC/X360/PS3) title. One day we started getting strange bug reports. Apparently, if you jumped down the roof at a very specific position, player would start to slide across the map. To make things more interesting, this was only happening on consoles, PC version was fine. After few minutes of investigation I narrowed it down to a fragment of code that looked roughly like this (don’t have access to the original code anymore, trying to recreate it from memory, that was player movement module):

float x = y / sfactor;
float vx = fmax(0.0001f, fmin(x, MAX_RESPONSE));

Looks innocent, but it’d break completely for y==0.0. The whole block has been added recently and the ‘sfactor‘ property was exposed to the editor and controlled by designers. As it turned out, it’s been set to 0.0 as well. If y == 0.0 and sfactor == 0.0, then x is NaN. fmax and fmin are, as you probably have guessed, floating-point versions of the min/max functions. For PC we were using a naive/reference implementation, ie:

float fmax(float a, b) { return a > b ? a : b; }
float fmin(float a, b) { return a < b ? a : b; }

Let’s see what happens in our case. fmin(NaN, MAX_RESPONSE) returns MAX_RESPONSE, as any comparison against NaN returns false. It’ll be fed to fmax and since it’s greater than 0.0001f, vx = MAX_RESPONSE.

Things are a little bit more interesting on PPC, though. If you coded for PowerPC, you’re aware of two facts:

  • it hates branches,
  • it has a ‘fsel’ instruction that allows for branchless floating-point code. Basically it ‘selects’ one of two given values based on another value (depending if it’s greater or less than zero).

The usual way of implementing fmin & fmax using fsel would be:

float fmax(float a, float b) { return fsel(a - b, a, b); }
float fmin(float a, float b) { return fsel(a - b, b, a); }

You can probably spot a problem already. If not, refer to this bit of fsel description (+my notes): “If the value in FRA [a – b in our case] is less than zero or is a NaN, floating point register FRT is set to the contents of floating-point register FRB [3rd argument]”. Think about what happens as our NaN flows through the fmin & fmax functions in this case:

  • fmin(x, MAX_RESPONSE): a – b is still NaN, so ‘a’ (x) is returned,
  • fmax(0.0001f, x): a – b is NaN, b (x) is returned.

In this case, NaN would just go through both functions and we ended up with an invalid vx. In this particular case it was an unfortunate coincidence that the original author used fmin(x, MAX_RESPONSE) — fmin(MAX_RESPONSE, x) would have been “fine”, but at least it helped us find the actual problem which was invalid value of the ‘sfactor‘ property (..and incompatibilities between fmin/fmax on different platforms).

MESIng with cache

December 22, 2014 – 7:12 am

(Please excuse the terrible pun, couldn’t help myself).

As we all know, computer cache is a touchy beast, seemingly little modifications to the code can result in major performance changes. I’ve been playing with performance monitoring counters recently (using Agner Fog’s library I mentioned before). I was mostly interested in testing how cmpxchg instruction behaves under the hood, but wanted to share some other tidbits as well.

Let’s assume we’re working with a simple spinlock code. There are a few ways of implementing one, each with slightly different characteristics. Let’s start with the most basic one:

void Lock()
    while(_InterlockedExchange(&mLock, 1) == 1)
        [..]// spin


  • “spin” code could be a whole post in itself and it’ll affect the performance. As mentioned, I was mostly interested in mechanics of cmpxchg, so I went with simple exponential backoff (if I wanted to amplify the effects of chosen ‘lock’ mechanism I could have gone with just spinning on single ‘pause’ instruction, but that felt too contrived).
  • InterlockedExchange compiles to xchg reg,dword ptr [mem]
  • Not posting code to Unlock, it’s the same in all experiments and boils down to setting mLock to 0 (atomically)

Let’s now think what happens if we have a high contention scenario with many threads (more importantly — many cores) trying to access the same variable and obtain the same lock. I’ll assume you’re familiar with the MESI protocol, so I’ll spare you the details (if not, Wikipedia has a decent write-up actually). The important part here is that as long as cache line containing mLock is in Modified or Exclusive state, we can read from it/write to it without having to communicate with other caches (we’ll need to write it back to main mem if it changes obviously, but that’s another issue). Sadly, with many threads banging on it, it’s quite unlikely, as different caches keep “stealing” the ownership from each other. As mentioned, InterlockedExchange compiles to xchg reg, [mem]. You might be surprised there’s no “lock” prefix, but it doesn’t matter in this particular case — Intel processors will automatically lock the bus “when executing an XCHG instruction that references memory” (see Intel Architecture Software Developer’s Manual Vol 3 for details). Not only we lock the bus, we also issue the infamous RFO message (Read For Ownership) in most cases (when we don’t own the line exclusively). This will cause all other processors to drop this line (set it to Invalid), so next time they try to access it, they’ll miss. Modern CPUs try to be smart about it and hide some of the associated overhead with store buffers and invalidate queues, but it still hurts.
Consider the following modification to our lock code:

while(mLock == 1 || _InterlockedExchange(&mLock, 1) == 1)

Before analyzing this change, let’s run a quick benchmark – quad core CPU, 4 threads, all fighting to access the same variable and increase it (500000 times each).

  • v1: ~64ms on average,
  • v2:  ~59ms on average,

Not huge, but significant difference and it actually increases with contention. That’s hardly surprising and actually well known, we’ve just implemented test-and-set (v1) and test and test-and-set locks (v2) [and if we want, we can complicate things further with tickets or array locks]. The idea here is we spin mostly on reading from local cache, so no need to communicate with other CPUs, we only do it when we think we have a chance of succeeding. Things get a little bit more interesting as the contention decreases. With 2 threads fighting for access, the results are as following:

  • v1: ~19ms
  • v2: ~23 ms

Uh, oh… The lesson here I guess is not to apply “one size fits all” solutions to everything. Lots of benchmarks out there tend to focus on super high contention scenarios. They are important sure, but sometimes they feel a little bit counter-intuitive as well. After all, if we have 4+ threads banging on the same lock, perhaps it’s a good idea to reduce the contention first? Treat the cause, not the symptom. It’s hard to come up with solutions that are clearly superior for all scenarios. There’s actually an interesting discussion at the Linux Kernel discussion list on this very subject (cmpxchg, not xchg, but similar principles apply, in the end they decided to reject TTAS). In case of ‘light’ contention, our xchg will succeed in majority of cases, so extra read actually hurts us more than it helps.

Let’s dig a little bit deeper now and run our test PMC snippets. I added a bunch of performance counters, mostly related to cache activity and ran the tests again. 4 threads (click to enlarge):





(Results for CPU 1 & 0 were very similar). As you can see there’s clearly more cache traffic in the TAS case, even though the instruction count is very similar. I added the following counters:

{161, S_ID3,  INTEL_IVY,    0,   3,     0,   0x24,       0x0C, "L2 RFOs"    },
{162, S_ID3,  INTEL_IVY,    0,   3,     0,   0xF2,       0x0F, "L2Evict" },
{163, S_ID3,  INTEL_IVY,    0,   3,     0,   0x27,       0x02, "RFO.S"},
{164, S_ID3,  INTEL_IVY,    0,   3,     0,   0x26,       0x1, "L2Miss"},
  • L2 RFOs = number of store RFO requests (=L1D misses & prefetches),
  • L2Evict = L2 lines evicted for any reason
  • L2Miss = take a guess

Let’s try with 2 threads next:





As you can see, there’s still less RFOs, but interestingly — the number of misses is almost the same and TTAS generates more instructions, obviously.

There’s one more way of implementing our spinlock and that’s a cmpxchg instruction:

while(_InterlockedCompareExchange(&mLock, 1, 0) == 1)

How do you think, is it closer to TAS or TTAS? First thought could be TTAS, after all it’s a very similar idea, we compare against expected value first, then exchange. There are few differences, though. For one, _InterlockedCompareExchange compiles to lock cmpxchg, so we lock the bus before reading. Also, it’s 1 fairly complicated instruction, not 2 or more. According to Agner Fog’s tables, lock cmpxchg is 9 uops (as compared to 7 for xchg). There are some more interesting (and perhaps surprising) properties, but first some benchmarks (v3). 4 threads:

cmpxchg (4 threads)

cmpxchg (4 threads)

It seems like it’s very close to the xchg instruction. This is what you could expect based on this paper on scalable locks from Intel, but to be honest, I was a little bit surprised at first, especially by the fact it seems to generate similar cache traffic. As it turns out — cmpxchg instruction itself is actually quite close to xchg as well (they work differently, but trigger similar mechanisms):

  •  cmpxchg implies an RFO, in all cases, even if comparison fails. Some confirmation here (LKML again) and it’s also what shows in PMC tests above,
  • another interesting question is — does lock cmpxchg always result in a write? Again, the answer seems to be “yes”. That’s based on Agner’s tables (1 p4 uop. p4 = memory write) and the fact that ops that lock the bus are expected to write to memory. There’s some more information here for example, if comparison fails, the destination operand is simply written back as if nothing happened.

The beauty of cmpxchg is that it does the comparison & swap atomically, so it’s perfect for more complicated scenarios (like MPMC containers, where we need to swap list head for example), but our case here is very simple, we just ping-pong between 0 & 1. When trying to obtain lock by using xchg, if it’s already taken, we’ll simply write 1 to it again, it doesn’t break anything, cmpxchg doesn’t really buy us much. I actually found a patent application for a FASTCMPXCHG instruction (from Intel engineers). The idea is that in some cases CPU replaces the whole load-compare-store chain with simple final store (AFAIK it’s not implemented in any hardware).

For some more benchmarks of various memory operations/different CPUs see also this Gist from Ryg.

Rust pathtracer

November 14, 2014 – 4:25 am

Last year I briefly described my adventure with writing a pathtracer in the Go language. This year, I decided to give Rust a try. It’s almost exact 1:1 port of my Go version, so I’ll spare you the details, without further ado – here’s a short list of observations and comparisons. As previously, please remember this is written from position of someone who didn’t know anything about the language 2 weeks ago and still is a complete newbie (feel free to point out my mistakes!):

  • Rust is much more “different” than most mainstream languages. It was the first time in years that I had to spend much time Googling and scratching my head to get a program even to compile. Go’s learning curve seemed much more gentle. One reason is that it’s still a very young, evolving language. In many cases information you find is outdated and relates to some older version (it changes a lot, too), so there’s lots of conflicting data out there. The other is unorthodox memory management system that takes a while to wrap your head around.
  • As mentioned – it still feels a little bit immature, with API and language mechanisms changing all the time. I’m running Windows version which probably makes me lagging behind even more. Enough to say, it’s quite easy to get a program that crashes when trying to start (and I’m quite sure it’s not the Rust code that causes the issues, it’s the generated binary.. It crashes before printing even the first message). It’s always the same code, too, accessing some spinlock guarded variable, it seems:
    00000000774EE4B4 8B 43 08         mov         eax,dword ptr [rbx+8]
    00000000774EE4B7 A8 01            test        al,1
    00000000774EE4B9 0F 85 B5 47 FD FF jne         00000000774C2C74
    00000000774EE4BF 8B C8            mov         ecx,eax
    00000000774EE4C1 2B CD            sub         ecx,ebp
    00000000774EE4C3 F0 0F B1 4B 08   lock cmpxchg dword ptr [rbx+8],ecx
    00000000774EE4C8 0F 85 9B 47 FD FF jne         00000000774C2C69
    00000000774EE4CE 48 8B 03         mov         rax,qword ptr [rbx]
    00000000774EE4D1 4C 89 AC 24 C0 00 00 00 mov         qword ptr [rsp+0C0h],r13
    00000000774EE4D9 33 ED            xor         ebp,ebp
    00000000774EE4DB 45 33 ED         xor         r13d,r13d
    00000000774EE4DE 48 83 F8 FF      cmp         rax,0FFFFFFFFFFFFFFFFh
    00000000774EE4E2 74 03            je          00000000774EE4E7
    00000000774EE4E4 FF 40 24         inc         dword ptr [rax+24h]  
  • Memory management, which is one of its distinctive features is both interesting & confusing at first. They seem to go back & forth on optional GC, but the canonical way is to use one of few types of smart pointers. Memory leaks and other issues are detected at compile time. Rust compiler in general is pretty good at detecting potential problems, once it builds, it’ll probably run fine. The only runtime error I encountered in my app was out of bounds array access. (It’s a good thing too as I’ve no idea how to debug my application… Don’t think there’s a decent debugger for Windows)
  • Unlike Go, it has operator overloading, but syntax is a little bit confusing to be honest. You don’t use the operator itself when overloading, you have to know what function name it corresponds to. E.g. operator-(Vector, Vector) is:
    impl Sub<Vector, Vector> for Vector
        fn sub(&self, other: &Vector) -> Vector
            Vector { x : self.x - other.x, y : self.y - other.y, z : self.z - other. z}

    Not sure what’s the rationale behind this, but it’s one more thing to remember.

  • Changing pointer types feels cumbersome at times. For example, let’s imagine we want to change a boxed pointer:
    struct Scene
        camera  : Box,

    to a reference. We now have to provide a lifetime specifier, so it changes to:

    struct Scene<'r>
        camera  : &'r mut Camera,

    …and you also have to modify your impl block (2 specifiers):

    impl<'r> Scene<'r>

    It seems a little bit redundant to me, even in C++ it’d be a matter of changing one typedef.

  • [EDIT, forgot about this one initially] Comparing references will actually try to compare referenced objects by value. If you want to compare the actual memory addresses you need to do this:
        if object as *const Sphere == light as *const Sphere // compares ptrs
        if object == light // compares objects
  • Rust code is almost exactly same length as Go, around 700  lines
  • Running tracer in multiple threads took more effort than with Go. By default, Rust’s tasks spawn native threads (was a little surprised when I opened my app in the Process Hacker and noticed I had 100+ threads running), you need to explicitly request “green” tasks. It also involved way more memory hacks. By default, Rust doesn’t allow for sharing mutable data (for safety reasons), the recommended way is to use channels for communication. I didn’t really feel like copying parts of framebuffer was a good idea, so had to resort to some “unsafe” hacks (I still clone immutable data). I quite like this approach, it’s now obvious what data can be modified by background threads. I’m not convinced I chose the most effective way, though, there’s no thread profiler yet (AFAIK).
  • Performance. Surprisingly, in my tests Rust was quite a bit slower than Go. Even disregarding the task pool/data sharing code, when running from a single thread, it takes 1m25s to render 128×128 image using Go and almost 3 minutes with Rust. With multiple threads, the difference is smaller, but still noticeable (43s vs 70s).
    [EDIT] Embarrassingly enough, turned out I was testing version with no optimizations. After compiling with -O Rust now renders the same picture in 34s instead of 70 (and 1m09s with 1 thread). I’ll leave the old figures, just to show that debug build still runs with decent speed.
  • Random stuff I liked:
    • data immutable by default. It makes it immediately obvious when it’s modified. E.g.
      let r = trace(&mut ray, &context.scene, &context.samples, u1, u2, &mut rng);
      Can you tell what’s modified inside trace function?
    • as mentioned – compiler is very diligent, once the app builds, there’s a good chance it’ll run fine. Error messages are clear & descriptive
    • pattern matching
  • I realize it might seem like I’m mostly praising Go and bashing Rust a little bit here, but that’s not the case. I’ll admit I couldn’t help but think it seemed immature compared to Go, but I realized it’s an unfair comparison. Go has been around for 5 years and I only started using it 12 months ago, so they had lots of time to iron out most wrinkles. Rust is a very ambitious project and I definitely hope it gains more popularity, but for the time being Go’s minimalism resonates with me better. I mostly code in C++ at work, this is a language that offers you 100 ways of shooting yourself in the foot. Working with Go, where it’s usually only one true way (and it involves blunt tools) is very refreshing. Rust sits somewhere in-between for the time being, it’ll be fascinating to see where it ends up.

Obligatory screenshot:


512×512, 256spp, 2x2AA

Source code can be downloaded here.

Hidden danger of the BSF instruction

October 26, 2014 – 5:49 am

Had a very interesting debugging session recently. I’ve been investigating some of external crash reports, all I had was a crash dump related to a fairly innocent-looking piece of code. Here’s a minimal snippet demonstrating the problem:

struct Tree
    void* items[32];

#pragma intrinsic(_BitScanForward)
__declspec(noinline) void* Grab(Tree* t, unsigned int n)
    unsigned int j = 0;
    _BitScanForward((unsigned long *)&j, n);
    return t->items[j];

Easy enough, right? Seemingly, nothing can go wrong here. We find first set bit and use to index our table. ‘n’ is 32-bit, so our index is guaranteed to be in the 0-31 range, so it’s all good. Well, why is it crashing in extreme rare cases then? Let’s take a look at generated assembly code (x64), maybe it’ll help decipher this madness:

and    DWORD PTR j$[rsp], 0
bsf    eax, edx
; 667  :     return t->items[j];
mov    rax, QWORD PTR [rcx+rax*8]
ret    0

Three measly instructions, nothing extraordinary here, right? Don’t click “read the rest” if you want to give it a try yourself.

Read the rest of this entry »

Z-Machine interpreter in Go

September 23, 2014 – 3:32 am

zork1Recently, I had an inspiring discussion with fellow programmers, we were talking about interesting side projects/programs to quickly “try out” new programming language/job interview tasks. One that’s been mentioned was coding a Z-machine interpreter that’s capable of playing Zork I. The Z-machine is a virtual machine developed by Joel Berez and Marc Blank, used for numerous Infocom text adventure games, most notably the Zork series. In all honesty, I’m probably a few years too young so didn’t get to play Zork when it was big (I did play old Sierra adventures back when you actually had to type commands, though, one of the the reasons I started to learn English was Police Quest I. Took me more than 3 months to finish this game). Few weeks later I had a whole weekend to myself and decided to give it a try. As it turned out — it really was a lot of fun. I also gained lots of respect for the Infocom guys, there are some really creative ideas there, especially given space/memory limitations (zork1.dat file I found was ~90k). At first I wanted to do it in Rust (language I wanted to experiment with), but in the end decided to play it safe, limit the number of unknowns and went with Go (my second time). It actually turned out to be a good choice, basic implementation is ~1500 lines of Go and comes with some nice features for free (like cycling through past commands with the up arrow). Went fairly smooth too, stumbled few times, mostly because of me missing some little detail (like call 0 == return false or some off-by-1 mistake when indexing properties). One that took me probably most time was subtle bug in the ‘change parent’ routine that’d cause the game to break apart after I had picked up something. Luckily, I found an easy repro case, if I didn’t pick up a water bottle, I could move the rug fine, otherwise, it’d complain about rug not being there. I didn’t want to spend time writing a fullblown debugger, it was a weekend project after all), so spent some time comparing instruction traces for “good” and “bad” runs, trying to see where they drift apart. Eventually coded a quick diff application (comparing it in notepad was too slow) and found what was going on, it was fairly smooth sailing after that.

debuggingThe good thing, it’s very easy to start with a basic framework that does nothing but advances IP accordingly and then keep on filling the gaps, adding implementation for required opcode types, opcodes themselves etc. I simply started with NOPs everywhere (with basic implementation calling panic(“NOP”)) and then kept on implementing until finally seeing the “you are standing in an open field of a white house” message. The good thing is, getting to this point requires implementing most of the basic functionality, it’s mostly adding opcodes after that (aka the easy stuff).

Big pieces that are still missing are save/restore, other than that it should be fairly complete (it’s version 3 only).

Useful links, if someone would like to give it a try:

A Byte Too Far

July 17, 2014 – 5:19 am

A short cautionary tale from today. I’ve been modifying some code and one of the changes I made was to use a type of Lol as a key in a map-like structure (key-pair container, uses < operator for comparisons). Structure itself looked like:

struct Lol
    byte tab[16];
    short cat;
    bool foo;

…and here’s the operator<

bool Lol::operator<(const Lol& other) const
    return(memcmp(this, &other, sizeof(other)) < 0);

The problem was – it seemed like sometimes, in seemingly random cases, we’d try to insert an instance of Lol to a container even though exactly the same element was already there. In other words (pseudo code):

container.insert(std::make_pair(lol, cat));
lol2 = lol;
auto it = container.find(lol2);
// In some cases it == container.end()!

As you’ve already guessed (or perhaps spotted it immediately) – the problem was caused by operator<. The “original” version of the Lol type didn’t have ‘foo’ member, it’s been added quite recently (*cough*by me*cough*). Can you guess why did it break?

Read the rest of this entry »

Going deeper – addendum

May 4, 2014 – 5:56 am

There’s been some comments to my previous post wondering about C++ compilers and their capabilities. Normally, I’m all for compiler bashing, in this case I’d probably cut them some slack. It’s easy to optimize when you’re focused on a single piece of code, way more difficult when you have to handle plethora of cases. On top of that, uops handled differently on different CPUs, e.g. in my limited tests Haswell seems to care less. Anyhow, I’d rather expect compilers to replace INC with ADD x,1 in most cases, I’d be much less optimistic with SIB byte elimination. MSVC seems a little inconsistent about it, it sometimes uses INC, sometimes ADD, not sure what determines that. Out of curiosity, I decided to use Matt Godbolt’s excellent Compiler Explorer to see how different compilers from the GCC family behave. Results:

  • GCC 4.9.0 eliminates both SIB byte & uses ADD instead of inc (it pretty much generates identical code as my final, hand optimized version)
  • Clang 3.2 eliminates SIB byte, but uses INC [mem]
  • g++ 4.4 – same as Clang

I didn’t really test the more exotic versions, follow the link if you’re interested.

Going deeper

April 27, 2014 – 5:57 am

Few weeks ago I encountered a discussion on a Polish gamedev forum — participants were wondering whether it’s faster to access stack or heap memory. I didn’t pay much attention (there should be no significant difference) until someone had posted a test case. Out of curiosity, I ran it and to my surprise discovered, it was consistently faster for buffers allocated on the stack. We’re not talking about few cycles here and there, too, the difference was almost 20% (Ivy Bridge laptop). Test itself is a little bit contrived, but turned out to be an interesting study. Code is exactly the same in both cases, we simply increment all elements of an array:

for(int i = 0; i < iterations; i++)
    for(int j = 0; j < arraySize; j++)
char stackArray[arraySize];
char* heapArray = new char[arraySize];

I refused to believe it was actually a memory access making a difference so decided it’s time to dig deeper. Let’s take a look at the very inner loop for these two cases, as it turns out it’s slightly different:

// Stack:
00D1100D BB 01 00 00 00   mov         ebx,1
00F11014 00 98 40 30 F1 00 add         byte ptr stackArray (0F13040h)[eax],bl
00F1101A 03 C3            add         eax,ebx
00F1101C 3B 05 3C 21 F1 00 cmp         eax,dword ptr [arraySize (0F1213Ch)]

// Heap:
00D11036 8B 0D 48 30 E1 00 mov         ecx,dword ptr [heapArray (0E13048h)]
00D1103E FE 04 01         inc         byte ptr [ecx+eax]
00D11041 40               inc         eax
00D11042 3B 05 3C 21 D1 00 cmp         eax,dword ptr [arraySize (0D1213Ch)]

As you can see — it’s pretty close, main difference seems to be using INC instead of ADD. Back in the old days, comparing performance was easy, we’d just see how many cycles INC/ADD costed. Pentium complicated things a little bit with U/V pairing and with modern out-of-order processors it’s even more tricky. Without going in gory details, CPUs can split instructions into smaller, more RISCy operations named micro-ops. add [mem], reg is a good example, it’ll be split into 4 uops (load, add, calc write address, store). To make things more interesting, some of these micro-ops can be then fused again into a single operation (some of pipeline stages can only process a limited number of uops, so this reduces bottlenecks). Different CPUs have different fusion capabilities, but my Ivy Bridge should be able to fuse our 4 uops back to 2. Let’s verify our assumptions using Agner’s MSR driver (I mentioned it before). Results from test run for the “stack version”, array size = 1024, 1 iteration:


Uops F.D = uops fused domain, fused uops count as 1
Fused uops = # of fused uops

As we can see, inner loop costs 4 uops per iteration (after fusion). Let’s see the results for inc byte ptr [ecx+eax]:


Ouch. As you can see, number of instructions is almost exactly the same, but we generate way more uops (6k vs 4k, 2 uops more per iteration) and micro-op fusion doesn’t seem to do a very good job. Where does the difference come from? As usually, in such case, I start with Agner Fog’s site. As it turns out, there’s some subtlety to memory store instructions – if they don’t use SIB byte, they only cost 1 uop, otherwise – it’s 2. If you look at our “heap code”, it’s clear we need a SIB byte (it’s necessary if there’s more than 1 pointer register), that means 2 uops. Let’s try to modify the assembly code so that we don’t use 2 registers:

mov eax, dword ptr heapArray
mov ecx, eax
add ecx, arraySize
inc byte ptr [eax]
inc eax
cmp eax, ecx
jb l1



Progress! We eliminated 1 uop per iteration. Still not exactly on par with the first version, but we’re getting there. The remaining difference is INC vs ADD. I actually asked Agner Fog about it, he rightfully pointed out it’s probably related to the fact INC needs to preserve the carry flag (for legacy reasons). (Sidenote: every time I ask Agner about something, he replies almost immediately… After that I imagine the volume of mail he must be getting, compare to the time it takes me to answer an email and start feeling bad). It’s also clearly noted in his “Instruction tables” doc (INC = 3 uops fused domain, ADD = 2) and Intel discourage using INC in their docs as well. Let’s replace INC with ADD and see the results:


That’s more like it! As you can see, we now generate 4 uops per iteration (same as the first version). The only thing that was still bothering me as the difference in the fused uop number (~2k here, ~3k in the first one). I figured it had something to do with cmp instruction using register (vs memory in the first one). Using “Instructions table” again we can notice that CMP m, r/i is actually not fused, while CMP r, r/i is. I also discovered another tool that’s helpful in such situations – Intel Architecture Code Analyzer. Compare output for cmp reg, mem & cmp reg, reg:

|   2^   | 0.3       |     | 0.5   0.5 | 0.5   0.5 |     |     | 0.8 |     |    | cmp eax, dword ptr [0x0]
|   1     | 0.3       |     |               |               |     |     | 0.8 |     |    | cmp eax, 0x400

^ means that micro-op fusion happened here (2 uops fused into 1). IACA doesn’t seem 100% reliable (e.g. it doesn’t seem to catch the INC vs ADD difference), but it’s another helpful tool in our collection.

Obviously, going to the micro-op level is not something you’ll be doing often (or ever, to be honest), it only makes sense if you’re actually writing assembly, otherwise it’s in the hands of the compiler. I still think it’s fun and an interesting way to understand how the modern CPUs work under the hood.

Patching binaries

November 11, 2013 – 6:24 am

There may come a time in game programmer’s life when he has to fix a bug in a library he doesn’t have the source code for. It doesn’t happen often, it might never happen, but it’s good to be prepared. If I remember correctly, I had to do it only two times, one was fairly recently. We were getting quite a few crash reports and were assured that fix in the third-party library was coming, but I decided to see if it’s possible to do anything about it in the meantime. Things were further complicated by the fact we’ve never seen this crash internally, it was all based on user reports (and it was quite rare in the wild, too). Started with investigating crash dumps in WinDbg. The crash itself was division by zero, it seemed like the code was not handling all the edge cases correctly. It’d load a value from table, do some transformation and divide by result, it worked fine in most cases, but would break if the value read from the table was zero, too (it’d pass all the transformations and come out as zero on the other end). We had no sources and no symbols, so I wasn’t even sure what was this function supposed to do, but it seemed like the array should not contain zeros in the first place. Now, I didn’t really care about 100% correct solution, as it was obvious I was treating symptoms, I just wanted something that’d eliminate crashes (and wouldn’t break rendering completely, I was fine with temporary artifacts). What I had to do was to squeeze in a test against zero, handle it and also set the original array element to something else than 0 (to cut the long story short, I found out about the last requirement in the process, it’d crash in another function without it). Easy, right? That’s like ~12 bytes worth of opcodes in x64. The block I was comfortable with modifying (didn’t want to mess with the whole function) was roughly 40-45  bytes, maybe a little bit more, so I had to find a way to shrink it down by ~25-30%. I will not focus on the actual modifications too much, as they’re not applicable for anyone else and – to stress this one more time – you do not need stuff like this often, if ever. Instead, I’ll try to present some of the tricks & tools of the trade that can come useful in other situations, too.

Let’s start with writing the code that does the same as the original fragment, but is smaller. Luckily for me, code was using additional registers (outside the EAX-EDI range), even though it was not operating on 64-bit numbers (so only using lower 32-bits). When using extended registers, we have to output an additional REX prefix, so most of the time opcodes are at least 1 byte longer than their 32-bit counterparts. Example:

mov ecx, eax            ; 8b c8 = 2 bytes
mov ecx, r8d            ; 41 8b c8 = 3 bytes 
                        ; (0x41 encodes default operand size 
                        ; (32-bit for mov) & extends the MODRM)

By changing parts of the code to operate on EAX-EDI I was able to get within 1 byte to my goal, but for the last stretch I had to resort to more risky modification involving using CDQ (1 byte opcode) instead of XOR EDX, EDX (2 bytes). They are equivalent, assuming we’re operating on positive numbers, which luckily was the case here. Surprisingly, x86 version was somewhat easier, I could not use “smaller” registers, but generated code was a little bit redundant, so I modified the algorithm slightly to do the same thing, but with less instructions.

Getting the final opcodes was trivial for x86, I simply used inline assembly and copy-pasted from the disassembly window. Could not do the same for x64 as MSVC does not support inline assembly in this mode (intrinsics only). Looking back, I should have just downloaded some x64 assembler, but if I did – I would not have discovered ODA. It’s great online disassembler supporting every platform you’ve ever coded for and a bunch you’ve never heard about. My only complaint is it sometimes takes a while to realize that opcodes have changed and still shows you the old code, but other than that – it’s simply awesome. x64 encoding is not terribly user friendly, especially when you need to generate instructions like INC BYTE PTR [R12+0x4], but I kept plowing through. Intel’s manuals are a good starting point, but I found OSDev Wiki to be a more concise reference.

For the actual editing I’ve used HTE for x86. It probably pushes the definition of oldschool a little bit too far (no mouse support…), but has a built-in disassembler, so that I could immediately verify my changes made sense. Could not find any hex editor/disassembler for 64-bits, so used my trusty xvi32 and the debugger for verification.

This brings us to the last point — how to set a breakpoint in an unknown piece of code, no function name, no symbols. Well, immediate window to the rescue! (Side note: I feel this is probably one of the most underappreciated features of Visual Studio. IME many of programmers complaining about MSVC debugger either do not use it often enough or do not use it to full potential). We know the opcodes, we can search for them in memory. Start with getting address range of the module you’re interested in (open Modules window, copy-paste). Now, in the immediate window we can use the memory search command. For example, let’s assume you’re looking for the mov ecx, eax instruction (in real life scenario, you’d probably want to choose something less common obviously) and you’re module address range is 0x003D0000-0x0044B000:
.S -W 0x003D0000 0x0044B000 0xc88b (-W = 16-bit number, -D = 32-bit).

All that’s left to do is opening the disassembly window and copy-pasting addresses returned by .S command (hopefully not too many of them) into the ‘Address’ field one-by-one. Shouldn’t take long to find a function we’re looking for. That was the last stage of my experiment, I could now verify the code was indeed running, I was able to modify data on the fly, prove that it did crash upon encountering zero in the array (remember, I have never actually experienced this bug myself, it’s all based on user error reports, hoping to just run into it was a fool’s errand). More importantly, I could verify it was no longer crashing after my changes and introduced no noticeable side effects.

Road trip 2013

October 30, 2013 – 5:24 am

Last summer we visited Alberta and BC, so this year it was time to go east. We’ve been driving and only had 9 days, so didn’t go all the way to the coast (something for 2014 perhaps?), but had a great trip anyhow. Itinerary was London-Kingston (1000 Islands cruise)-Ottawa-Montreal-Quebec City. A little bit over 2100kms, I’ve not been driving every day though, so it wasn’t too demanding. Ottawa & Montreal were nice, but it’s QC that was the highlight of our trip. It’s a charming little city with a very European feel (old town at least), it was nice to see buildings older than 150 years for a change. We happened to be in Ottawa just in time for The Canada Day, which was a nice experience as well. Some photos (more here):