Category Archives: Uncategorized

Over the past year or so I’ve almost doubled the speed of SpiderMonkey’s JavaScript parser. I did this by speeding up both the scanner (bug 564369, bug 584595, bug 588648, bug 639420,bug 645598) and the parser (bug 637549). I used patch stacks in several of those bugs, and so in those six bugs I actually landed 28 changesets.

Notable things about scanning JavaScript code

Before I explain the changes I made, it will help to explain a few notable things about scanning JavaScript code.

JavaScript is encoded using UCS-2. This means that each character is 16 bits.

There are several character sequences that indicate the end of a line (EOL): ‘\n’, ‘\r’, ‘\r\n’, \u2028 (a.k.a. LINE_SEPARATOR), and \u2029 (a.k.a. PARA_SEPARATOR). Note that ‘\r\n’ is treated as a single character.

JavaScript code is often minified, and the characteristics of minified and non-minified code are quite different. The most important difference is that minified code has much less whitespace.

Scanning improvements

Before I made any changes, there were two different modes in which the scanner could operate. In the first mode, the entire character stream to be scanned was already in memory. In the second, the scanner read the characters from a file in chunks a few thousand chars long. Firefox always uses the first mode (except in the rare case where the platform doesn’t support mmap or an equivalent function), but the JavaScript shell used the second. Supporting the second made made things complicated in two ways.

It was possible for an ‘\r\n’ EOL sequence to be split across two chunks, which required some extra checking code.

The scanner often needs to unget chars (up to six chars, due to the lookahead required for \uXXXX sequences), and it couldn’t unget chars across a chunk boundary. This meant that it used a six-char unget buffer. Every time a char was ungotten, it would be copied into this buffer. As a consequence, every time it had to get a char, it first had to look in the unget buffer to see if there was one or more chars that had been previously ungotten. This was an extra check (and a data-dependent and thus unpredictable check).

The first complication was easy to avoid by only reading N-1 chars into the chunk buffer, and only reading the Nth char in the ‘\r\n’ case. But the second complication was harder to avoid with that design. Instead, I just got rid of the second mode of operation; if the JavaScript engine needs to read from file, it now reads the whole file into memory and then scans it via the first mode. This can result in more memory being used but it only affects the shell, not the browser, so it was an acceptable change. This allowed the unget buffer to be completely removed; when a character is ungotten now the scanner just moves back one char in the char buffer being scanned.

Another improvement was that in the old code, there was an explicit EOL normalization step. As each char was gotten from the memory buffer, the scanner would check if it was an EOL sequence; if so it would change it to ‘\n’, if not, it would leave it unchanged. Then it would copy this normalized char into another buffer, and scanning would proceed from this buffer. (The way this copying worked was strange and confusing, to make things worse.) I changed it so that getChar() would do the normalization without requiring the copy into the second buffer.

The scanner has to detect EOL sequences in order to know which line it is on. At first glance, this requires checking every char to see if it’s an EOL, and the scanner uses a small look-up table to make this fast. However, it turns out that you don’t have to check every char. For example, once you know that you’re scanning an identifier, you know that if you hit an EOL sequence you’ll immediately unget it, because that marks the end of the identifier. And when you unget that char you’ll undo the line update that you did when you hit the EOL. This same logic applies in other situations (eg. parsing a number). So I added a function getCharIgnoreEOL() that doesn’t do the EOL check. It has to always be paired with ungetCharIgnoreEOL() and requires some care as to where it’s used, but it avoids the EOL check on more than half the scanned chars.

As well as detecting where each token starts and ends, for a lot of token kinds the scanner has to compute a value. For example, after scanning the character sequence ” 123 ” it has to convert that to the number 123. The old scanner would copy the chars into a temporary buffer before calling the function that did the conversion. This was unnecessary — the conversion function didn’t even require NULL-terminated strings because it gets passed the length of the string being converted! Also, the old scanner was using js_strtod() to do the number conversion. js_strtod() can convert both integers and fractional numbers, but its quite slow and overkill for integers. And when scanning, even before converting the string to a number, we know if the number we just scanned was an integer or not (by remembering if we saw a ‘.’ or exponent). So now the scanner instead calls GetPrefixInteger() which is much faster. Several of the tests in Kraken involve huge arrays of integers, and this made a big difference to them.

There’s a similar story with identifiers, but with an added complication. Identifiers can contain \uXXXX chars, and these need to be normalized before we do more with the string inside SpiderMonkey. So the scanner now remembers whether a \uXXXX char has occurred in an identifier. If not, it can work directly (temporarily) with the copy of the string inside the char buffer. Otherwise, the scanner will rescan the identifier, normalizing and copying it into a new buffer. I.e. the scanner de-optimizes the (very) rare case in order to avoid the copying in the common case.

JavaScript supports decimal, hexadecimal and octal numbers. The number-scanning code handled all three kinds in the same loop, which meant that it checked the radix every time it scanned another number char. So I split this into three parts, which make it both faster and easier to read.

Although JavaScript chars are 16 bits, the vast majority of chars you see are in the first 128 chars. This is true even for code written in non-Latin scripts, because of all the keywords (e.g. ‘var’) and operators (e.g. ‘+’) and punctuation (e.g. ‘;’). So it’s worth optimizing for those. The main scanning loop (in getTokenInternal()) now first checks every char to see if its value is greater than 128. If so, it handles it in a side-path (the only legitimate such chars are whitespace, EOL or identifier chars, so that side-path is quite small). The rest of getTokenInternal() can then assume that it’s a sub-128 char. This meant I could be quite aggressive with look-up tables, because having lots of 128-entry look-up tables is fine, but having lots of 65,536-entry look-up tables would not be. One particularly important look-up table is called firstCharKinds; it tells you what kind of token you will have based on the first non-whitespace char in it. For example, if the first char is a letter, it will be an identifier or keyword; if the first char is a ‘0’ it will be a number; and so on.

Another important look-up table is called oneCharTokens. There are a handful of tokens that are one-char long, cannot form a valid prefix of another token, and don’t require any additional special handling: ;,?[]{}(). These account for 35–45% of all tokens seen in real code! The scanner can detect them immediately and use another look-up table to convert the token char to the internal token kind without any further tests. After that, the rough order of frequency for different token kinds is as follows: identifiers/keywords, ‘.’, ‘=’, strings, decimal numbers, ‘:’, ‘+’, hex/octal numbers, and then everything else. The scanner now looks for these token kinds in that order.

That’s just a few of the improvements, there were lots of other little clean-ups. While writing this post I looked at the old scanning code, as it was before I started changing it. It was awful, it’s really hard to see what was happening; getChar() was 150 lines long because it included code for reading the next chunk from file (if necessary) and also normalizing EOLs.

In comparison, as well as being much faster, the new code is much easier to read, and much more DFA-like. It’s worth taking a look at getTokenInternal() in jsscan.cpp.

Parsing improvements

The parsing improvements were all related to the parsing of expressions. When the parser parses an expression like “3” it needs to look for any following operators, such as “+”. And there are roughly a dozen levels of operator precedence. The way the parser did this was to get the next token, check if it matched any of the operators of a particular precedence, and then unget the token if it didn’t match. It would then repeat these steps for the next precedence level, and so on. So if there was no operator after the “3”, the parser would have gotten and ungotten the next token a dozen times! Ungetting and regetting tokens is fast, because there’s a buffer used (i.e. you don’t rescan the token char by char) but it was still a bottleneck. I changed it so that the sub-expression parsers were expected to parse one token past the end of the expression, instead of zero tokesn past the end. This meant that the repeated getting/ungetting could be avoided.

These operator parsers are also very small. I inlined them more aggressively, which also helped quite a bit.

Results

I had some timing results but now I can’t find them. But I know that the overall speed-up from my changes was about 1.8x on Chris Leary’s parsemark suite, which takes code from lots of real sites, and the variation in parsing times for different codebases tends not to vary that much.

Many real websites, e.g. gmail, have MB of JS code, and this speed-up will probably save one or two tenths of a second when they load. Not something you’d notice, but certainly something that’ll add up over time and help make the browser feel snappier.

Tools

I used Cachegrind to drive most of these changes. It has two features that were crucial.

First, it does event-based profiling, i.e. it counts instructions, memory accesses, etc, rather than time. When making a lot of very small improvements, noise variations often swamp the effects of the improvements, so being able to see that instruction counts are going down by 0.2% here, 0.3% there, is very helpful.

Second, it gives counts of these events for individual lines of source code. This was particularly important for getTokenInternal(), which is the main scanning function and has around 700 lines; function-level stats wouldn’t have been enough.

Bug 609532 changed the way the JavaScript shell is built so that compile warnings are treated as errors. We already had a zero-tolerance policy for compile warnings in js/src/, but they tend to creep in, especially on Windows, because most people develop on Mac or Linux. Already at least one Windows build turned red because of a warning, and it was immediately fixed by the dev responsible. Previously that warning would have lasted for days or weeks until someone on Windows got sick enough of it to fix it.

I’d love to see the same thing done for the entire browser, but judging by the reams of compile warnings that go by when building the browser, this won’t happen any time soon.

Oh, and if you don’t know about make -s (a.k.a. make --silent or make --quiet), you should try it. It’s indispensible!

This is for code generated by JaegerMonkey. I know very little about JaegerMonkey’s code generation so I don’t have any good suggestions for reducing it. As I understand it very little effort has been made to minimize the size of the generated code so there may well be some easy wins there.

02.67% (28,618,752B) NewOrRecycledNode() (jsparse.cpp:670)

This is for JSParseNode, the basic type from which JS parse trees are constructed. Bug 626932 is open to shrink JSParseNode; there are a couple of good ideas but not much progress has been made. I hope to do more here but probably not in time for Firefox 4.0.

Shapes are a structure used to speed up JS property accesses. Increasing the MAX_HEIGHT constant from 64 to 128 (which reduces the number of JS objects that are converted to “dictionary mode”, and thus the number of Shapes that are allocated) may reduce this by 3 or 4 MB with negligible speed cost. I opened bug 630456 for this.

Each JS function has a JSFunction associated with it, and each JSFunction has a JSScript associated with it. Each of them stores various bits of information about the function. I don’t have any good ideas for how to shrink these structures. Both of them are reasonably large, with lots of fields.

Each function compiled by JaegerMonkey also has some additional information associated with it, including all the inline caches. This is allocated here. Somegoodprogress has already been made here, and I have somemoreideas for getting it down a bit further.

These entries are for space used during JS scanning (a.k.a. lexing, tokenizing). Identifiers and strings get atomized, i.e. put into a table so there’s a single copy of each one. Take an identifier as an example. It starts off stored in a buffer of characters. It gets scanned and copied into a js::Vector, with any escaped chars being converted along the way. Then the copy in the js::Vector is atomized, which involves copying it again into a malloc’d buffer of just the right size. I thought about avoiding this copying in bug 588648, but it turned out to be difficult. (I did manage to remove another extra copy of every character, though!)

In summary, there is definitely room for more improvement. I hope to get a few more space optimizations in before Firefox 4.0 is released, but there’ll be plenty of other work to do afterwards. If anyone can see other easy wins for the entries above, I’d love to hear about them.

T.3670 and T.3703 are clearly the same function, one which must be auto-generated by GCC but given different randomized suffixes in different builds. These entries are uninteresting and I plan to add an option to cg_diff that allows the user to munge function names with a search-and-replace expression so I can get rid of them.

But I’d like to know what the are first, so I can talk about them in the cg_diff documentation. Does anybody know? I tried googling, but it’s a very hard thing to find out with a search engine. (If someone can find something about it with a search engine I’d love to know what search term you used.)

I’m worried about Firefox 4.0’s memory consumption. Bug 598466 indicates that it’s significantly higher than Firefox 3.6’s memory consumption. So I did some profiling with Massif, a memory profiler built with Valgrind.

My test run involved a Firefox profile in which 20 tabs were open to random comics from http://www.cad-comic.com/cad/. This is a site that uses lots of JavaScript code. I ran a 64-bit version of Firefox on a Ubuntu 10.10 machine.

--smc-check=all tells Valgrind that the program may use self-modifying code (or, in Firefox’s case, overwrite dynamically generated code).

--trace-children tells Valgrind to trace into child processes exec’d by the program. This is necessary because optg64/dist/bin/firefox is a wrapper script.

--tool=massif tells Valgrind to run Massif.

--pages-as-heap=yes tells Massif to profile allocations of all memory at the page level, rather than just profiling the heap (ie. memory allocated via malloc/new). This is important because the heap is less than half of Firefox’s memory consumption.

--detailed-freq=1000000 tells Massif to do detailed snapshots (which are more informative but more costly) only every 1,000,000th snapshot, which is less often than the default of every 10th snapshot. This makes it run a bit faster. This is fine because Massif always takes a detailed snapshot at the peak memory consumption point, and that’s the one I’m interested in.

optg64/ is the name of my build directory.

-P cad20 tells Firefox to use a particular profile that I set up appropriately.

-no-remote tells Firefox to start a new instance; this is necessary because I had a Firefox 3.6 process already running.

Massif produced a number of files, one per invoked process. They have names like massif.out.22722, where the number is the process ID. I worked out which one was the main Firefox executable; this is not hard because the output file has the invoked command on its second line. I then viewed it in two ways. The first was with Massif’s ms_print script, using this command:

ms_print massif.out.22722

This produces a text representation of the information that Massif collects.

The second was with the massif-visualizer program, which is not part of the Valgrind distribution, but is available here. The information it shows is much the same as that shown by ms_print, but it’s much prettier. Below is a screenshot that shows the basic progression of the memory consumption (click on it for a full-size version).

At the peak memory usage point, a total of 1,297,612,808 bytes were mapped.

I went through the detailed snapshot taken at the point of peak memory consumption. Massif takes the stack trace of every memory allocation in the program, and collapses them into a tree structure in which common stack trace prefixes are merged. See the Massif user manual for more details of this tree structure; what’s relevant for this blog post is that I (manually) picked out various places in the code that cause significant amounts of memory to be mapped. These places together cover 68.85% (893,463,472 bytes) of the total mapped memory; the other 31.15% was taken up by smaller allocations that are less worth singling out. Each place contains a partial stack trace as identification. I’ve listed them from largest to smallest.

This is for thread stacks. Robert O’Callahan and Chris Jones tell me that Linux thread stacks are quite large (8MB?) but although that space is mapped, most of it won’t be committed (i.e. actually used).

I’m hoping that someone (or multiple people) who reads this will be able to identify places where memory consumption can be reduced. I’m happy to provide the raw data file to anyone who asks for it, though I also encourage people to try Massif themselves on different workloads.

Update. I forgot to mention that there was also the plugin-container process that ran in parallel to the main Firefox process. It was invoked by Firefox like so:

It allocated 458,676,874 bytes at peak. 62.7% was due to the loading of shared objects, 12.8% was due to thread stacks, and the remaining 24.5% was due to unknown allocation sites (probably because the flash binary was missing symbols) and allocations too small to be worth singling out.

On i386, Nanojit has two basic modes of operation: SSE, and non-SSE. Non-SSE is for old machines that don’t support SSE instructions. (It might actually be SSE2 instructions, I’m not sure.) My two machines both support SSE and so the non-SSE is never exercised unless I specify the environment variable X86_FORCE_SSE=no. Since this invocation doesn’t exactly roll off the fingertips, I don’t do it often. It’s also easy to mistype, in which case the normal SSE code will be run but I probably won’t notice and so I’m testing something different to what I think I am testing.

I recently committed a patch (bug 516348) that broke the non-SSE mode. (It may have also broken the SSE mode, but in a less obvious way.) Whenever I land a patch that breaks something, I try to work out if I could have avoided the breakage through a better process. In this case I could have, through automation. I now have the following set of aliases and functions in my .bashrc:

The code is boring. For those reading closely, it relies on the fact that I always put different builds in the directories debug32/, opt32/, debug64/, opt64/. And I skip check-data-format-tofte.js because it fails if you’re in a non-US timezone, see bug 515214.

I already had ‘jsdtt32’ et al, each of which tests a single configuration. But now with a single command ‘jsatt’ (which is short for “JavaScript All trace-tests”) I can run the JS trace-tests on 6 different configurations on a single x86-64 machine: 32-bit debug (SSE), 32-bit debug (non-SSE), 64-bit debug, 32-bit optimised (SSE), 32-bit optimised (non-SSE), 64-bit optimised. And it builds them to make sure they’re all up-to-date.

It’s only a small process change for me, but it means that it’s unlikely I will break any of these configurations in the future, or at least, not in a way that shows up in the trace-tests.

With the Valgrind-on-Mac support coming along nicely, it’s worth addressing another widely-used platform: Windows. Will Valgrind work on Windows any time soon? There are actually two answers: (a) hell no, and (b) it already does (sort of).

The patch I merged from the Darwin branch onto the trunk yesterday was 28,300 lines. And that was almost entirely new code, because I’d done a lot of work to synchronize the branch and trunk so that all non-addition changes had been dealt with. Greg Parker spent over four years, off and on, working on the original port, and I spent close to three months full time cleaning it up, and Julian Seward also pitched in a bit. I roughly estimate the Darwin port represents at least 1,000 person-hours of work, possibly much more.

And Mac OS X is a lot closer to Linux than Windows is. Also, the Mac OS X kernel is open source, which makes a port much easier. A Valgrind-on-Windows port would therefore be an enormous undertaking, one that is unlikely to happen soon, if ever. That is how we get answer (a) above.

However, although Valgrind doesn’t run on Windows, it is possible to run Windows programs under Valgrind, thanks to Wine — you run the Windows program under Wine, and Wine under Valgrind. The development (trunk) versions of both Valgrind and Wine now have enough awareness of each other that they can apparently be used together. I say “apparently” because I haven’t tried it myself, but I know that others have had some success. But please note that this is fairly new and experimental, and should only be tried by those not afraid to get their hands dirty (this page has more details). And that’s how we get the answer (b) above.

Update (Jan 19): Hmm, I wasn’t expecting this post to make it onto Planet Mozilla, as I wrote it two days before I requested that my blog be syndicated. Well, at least it didn’t take you long to read 🙂