Sådan fungerer JavaScript: Under motorhjelmen på V8-motoren

I dag skal vi se under hætten på JavaScript's V8-motor og finde ud af, hvordan JavaScript udføres nøjagtigt.

I en tidligere artikel lærte vi, hvordan browseren er struktureret og fik et overblik på højt niveau af Chromium. Lad os sammenfatte lidt, så vi er klar til at dykke herinde.

Baggrund

Webstandarder er et sæt regler, som browseren implementerer. De definerer og beskriver aspekter af World Wide Web.

W3C er et internationalt samfund, der udvikler åbne standarder for Internettet. De sørger for, at alle følger de samme retningslinjer og ikke behøver at støtte dusinvis af helt forskellige miljøer.

En moderne browser er et ganske kompliceret stykke software med en kodebase på titusindvis af linjer med kode. Så det er opdelt i mange moduler, der er ansvarlige for forskellig logik.

Og to af de vigtigste dele af en browser er JavaScript-motoren og en gengivelsesmotor.

Blink er en gengivelsesmotor, der er ansvarlig for hele gengivelsesrørledningen inklusive DOM-træer, stilarter, begivenheder og V8-integration. Det analyserer DOM-træet, løser stilarter og bestemmer den visuelle geometri for alle elementerne.

Mens der løbende overvåges dynamiske ændringer via animationsrammer, maler Blink indholdet på din skærm. JS-motoren er en stor del af browseren - men vi er ikke kommet ind i disse detaljer endnu.

JavaScript-motor 101

JavaScript-motoren udfører og kompilerer JavaScript til native maskinkode. Hver større browser har udviklet sin egen JS-motor: Googles Chrome bruger V8, Safari bruger JavaScriptCore, og Firefox bruger SpiderMonkey.

Vi arbejder især med V8 på grund af dets anvendelse i Node.js og Electron, men andre motorer er bygget på samme måde.

Hvert trin inkluderer et link til den kode, der er ansvarlig for det, så du kan blive fortrolig med kodebasen og fortsætte forskningen ud over denne artikel.

Vi vil arbejde med et spejl af V8 på GitHub, da det giver en praktisk og velkendt brugergrænseflade til at navigere i kodebasen.

Forberedelse af kildekoden

Den første ting V8 skal gøre er at downloade kildekoden. Dette kan gøres via et netværk, cache eller servicearbejdere.

Når koden er modtaget, skal vi ændre den på en måde, som compileren kan forstå. Denne proces kaldes parsing og består af to dele: scanneren og selve parseren.

Scanneren tager JS-filen og konverterer den til listen over kendte tokens. Der er en liste over alle JS-tokens i filen Keywords.txt.

Parseren samler den op og opretter et abstrakt syntaks-træ (AST): en trærepræsentation af kildekoden. Hver knude i træet angiver en konstruktion, der forekommer i koden.

Lad os se på et simpelt eksempel:

function foo() { let bar = 1; return bar; }

Denne kode vil producere følgende træstruktur:

Du kan udføre denne kode ved at udføre en forudbestillingsgennemgang (rod, venstre, højre):

  1. Definer foofunktionen.
  2. Erklær barvariablen.
  3. Tildel 1til bar.
  4. Gå tilbage barfra funktionen.

Du vil også se VariableProxy- et element, der forbinder den abstrakte variabel med et sted i hukommelsen. Processen med at løse VariableProxykaldes Scope Analysis .

I vores eksempel vil resultatet af processen alle være VariableProxypegende på den samme barvariabel.

Just-in-Time (JIT) paradigmet

For at din kode skal udføres, skal programmeringssproget generelt omdannes til maskinkode. Der er flere tilgange til, hvordan og hvornår denne transformation kan ske.

Den mest almindelige måde at omdanne koden på er at udføre kompilering på forhånd. Det fungerer nøjagtigt som det lyder: koden omdannes til maskinkode før udførelsen af ​​dit program under kompileringsfasen.

Denne tilgang bruges af mange programmeringssprog som C ++, Java og andre.

On the other side of the table, we have interpretation: each line of the code will be executed at runtime. This approach is usually taken by dynamically typed languages like JavaScript and Python because it’s impossible to know the exact type before execution.

Because ahead-of-time compilation can assess all the code together, it can provide better optimization and eventually produce more performant code. Interpretation, on the other side, is simpler to implement, but it’s usually slower than the compiled option.

To transform the code faster and more effectively for dynamic languages, a new approach was created called Just-in-Time (JIT) compilation. It combines the best from interpretation and compilation.

While using interpretation as a base method, V8 can detect functions that are used more frequently than others and compile them using type information from previous executions.

However, there is a chance that the type might change. We need to de-optimize compiled code and fallback to interpretation instead (after that, we can recompile the function after getting new type feedback).

Let's explore each part of JIT compilation in more detail.

Interpreter

V8 uses an interpreter called Ignition. Initially, it takes an abstract syntax tree and generates byte code.

Byte code instructions also have metadata, such as source line positions for future debugging. Generally, byte code instructions match the JS abstractions.

Now let's take our example and generate byte code for it manually:

LdaSmi #1 // write 1 to accumulator Star r0 // read to r0 (bar) from accumulator Ldar r0 // write from r0 (bar) to accumulator Return // returns accumulator

Ignition has something called an accumulator — a place where you can store/read values.

The accumulator avoids the need for pushing and popping the top of the stack. It’s also an implicit argument for many byte codes and typically holds the result of the operation. Return implicitly returns the accumulator.

You can check out all the available byte code in the corresponding source code. If you’re interested in how other JS concepts (like loops and async/await) are presented in byte code, I find it useful to read through these test expectations.

Execution

After the generation, Ignition will interpret the instructions using a table of handlers keyed by the byte code. For each byte code, Ignition can look up corresponding handler functions and execute them with the provided arguments.

As we mentioned before, the execution stage also provides the type feedback about the code. Let’s figure out how it’s collected and managed.

First, we should discuss how JavaScript objects can be represented in memory. In a naive approach, we can create a dictionary for each object and link it to the memory.

However, we usually have a lot of objects with the same structure, so it would not be efficient to store lots of duplicated dictionaries.

To solve this issue, V8 separates the object's structure from the values itself with Object Shapes (or Maps internally) and a vector of values in memory.

For example, we create an object literal:

let c = { x: 3 } let d = { x: 5 } c.y = 4

In the first line, it will produce a shape Map[c] that has the property x with an offset 0.

In the second line, V8 will reuse the same shape for a new variable.

After the third line, it will create a new shape Map[c1] for property y with an offset 1 and create a link to the previous shape Map[c] .

In the example above, you can see that each object can have a link to the object shape where for each property name, V8 can find an offset for the value in memory.

Object shapes are essentially linked lists. So if you write c.x, V8 will go to the head of the list, find y there, move to the connected shape, and finally it gets x and reads the offset from it. Then it’ll go to the memory vector and return the first element from it.

As you can imagine, in a big web app you’ll see a huge number of connected shapes. At the same time, it takes linear time to search through the linked list, making property lookups a really expensive operation.

To solve this problem in V8, you can use the Inline Cache (IC).It memorizes information on where to find properties on objects to reduce the number of lookups.

You can think about it as a listening site in your code: it tracks all CALL, STORE, and LOAD events within a function and records all shapes passing by.

The data structure for keeping IC is called Feedback Vector. It’s just an array to keep all ICs for the function.

function load(a) { return a.key; }

For the function above, the feedback vector will look like this:

[{ slot: 0, icType: LOAD, value: UNINIT }]

It’s a simple function with only one IC that has a type of LOAD and value of UNINIT. This means it’s uninitialized, and we don’t know what will happen next.

Let’s call this function with different arguments and see how Inline Cache will change.

let first = { key: 'first' } // shape A let fast = { key: 'fast' } // the same shape A let slow = { foo: 'slow' } // new shape B load(first) load(fast) load(slow)

After the first call of the load function, our inline cache will get an updated value:

[{ slot: 0, icType: LOAD, value: MONO(A) }]

That value now becomes monomorphic, which means this cache can only resolve to shape A.

After the second call, V8 will check the IC's value and it'll see that it’s monomorphic and has the same shape as the fast variable. So it will quickly return offset and resolve it.

The third time, the shape is different from the stored one. So V8 will manually resolve it and update the value to a polymorphic state with an array of two possible shapes.

[{ slot: 0, icType: LOAD, value: POLY[A,B] }]

Now every time we call this function, V8 needs to check not only one shape but iterate over several possibilities.

For the faster code, you can initialize objects with the same type and not change their structure too much.

Note: You can keep this in mind, but don’t do it if it leads to code duplication or less expressive code.

Inline caches also keep track of how often they're called to decide if it’s a good candidate for optimizing the compiler — Turbofan.

Compiler

Ignition only gets us so far. If a function gets hot enough, it will be optimized in the compiler, Turbofan, to make it faster.

Turbofan takes byte code from Ignition and type feedback (the Feedback Vector) for the function, applies a set of reductions based on it, and produces machine code.

As we saw before, type feedback doesn’t guarantee that it won’t change in the future.

For example, Turbofan optimized code based on the assumption that some addition always adds integers.

But what would happen if it received a string? This process is called deoptimization. We throw away optimized code, go back to interpreted code, resume execution, and update type feedback.

Summary

In this article, we discussed JS engine implementation and the exact steps of how JavaScript is executed.

To summarize, let’s have a look at the compilation pipeline from the top.

We’ll go over it step by step:

  1. It all starts with getting JavaScript code from the network.
  2. V8 parses the source code and turns it into an Abstract Syntax Tree (AST).
  3. Based on that AST, the Ignition interpreter can start to do its thing and produce bytecode.
  4. På det tidspunkt begynder motoren at køre koden og indsamle typefeedback.
  5. For at få det til at køre hurtigere kan bytekoden sendes til optimeringscompileren sammen med feedbackdata. Optimeringscompileren antager visse antagelser baseret på den og producerer derefter meget optimeret maskinkode.
  6. Hvis en af ​​antagelserne på et eller andet tidspunkt viser sig at være forkert, optimeres den optimerende kompilator og vender tilbage til tolken.

Det er det! Hvis du har spørgsmål om et bestemt stadium eller ønsker at vide flere detaljer om det, kan du dykke ned i kildekoden eller slå mig op på Twitter.

Yderligere læsning

  • "Life of a script" -video fra Google
  • Et crashkursus i JIT-kompilatorer fra Mozilla
  • Fin forklaring på Inline Caches i V8
  • Fantastisk dyk i objektformer