SlideShare una empresa de Scribd logo
1 de 42
AOT-compilation with V8
Phil Eaton
Engineer & Manager at Capsule8
notes.eatonphil.com
@phil_eaton
Dynamic languages == interpreter?
Lots of dynamic languages have AOT compilers!
● And produce native binaries
● Python -> Cython
● Java -> Graal
● Common Lisp -> SBCL
● Scheme -> Chicken Scheme
Static types & Compilation
Case study: Cython
● Compiles Python to C using libpython
● Produces a single binary
● Simple FFI
○ Though not as simple as Chicken Scheme
● Superset of Python
○ Pure Python: OK
○ Optional types for more efficient code: OK
Me vs. team of PhDs over years?
Not really trying to compete on speed
AOT-compilation can help any language
● Simplify deployment & packaging
● Simplify FFIs
● Make performance more predictable
○ Compared to JIT interpreters
AOT-compilation and dynamic languages cont.
● With additional sacrifices to dynamism e.g.:
○ No dynamic imports
○ Optional types
● Can get:
○ Relatively efficiently generated code with little effort
○ Smaller binaries/output
My background
● Working on a Scheme interpreter in 2017
● Wanted to add a compiler backend
● Process made trivial by using
○ Existing parser
○ Interpreter runtime as a library
Realized this is how (e.g.) Cython works...
Nothing like this exists for JavaScript That I know of
3rd party
JavaScript parser
Source code AST Fancy new
compiler
C++ & V8
Final product:
Native code
First pass
Jsc v0
● Proof-of-concept ES5 compiler
○ Written in Rust, uses an existing ES5 parser frontend
● Targets native Node addons in C++
○ Uses node-gyp
● Uses a 1-line entrypoint to load and run the addon
● Completely type unaware
○ Not even leaf-type propagation
Supported functionality
● Functions and function calls
● Basic tail-call optimization
● Var declarations
● Many primitive operators
● Object, array, number, string, boolean and null literals
● Access to Node builtins via `global`
● Basic source-to-source comments for debugging generated output
Unsupported functionality
● Specialized functions
● Imports
● Prototype functions/nested functions/closures
● Whole bunch of other stuff
Example
function fib(n, a, b) {
if (n == 0) { return a; }
if (n == 1) { return b; }
return fib(n - 1, b, a + b);
}
function main() {
console.log(fib(50, 0, 1));
}
Example cont.
$ jsc fib.js
$ cat build/fib.js
require("build/Release/fib.node").jsc_main()
$ node build/fib.js
12586269025
Generated code
https://github.com/eatonphil/jsc#code-produced (old commit)
Analysis: the good
● It works!
● V8 makes compiling to C++ dead simple!
○ Object representation: V8!
■ String::NewFromUtf8(isolate, "Boolean")
■ Number::New(isolate, 0)
○ Memory management: V8!
● Source-to-source commenting is helpful
○ // return a;
args.GetReturnValue().Set(a_2);
return;
Analysis: the bad
● Relatively bloated code
○ 5 LOC JavaScript -> 54 LOC C++
● TONS of redundant casting, moves
● What is going on with the Boolean check???
○ Local<Context> ctx_5 = isolate->GetCurrentContext();
Local<Object> global_6 = ctx_5->Global();
Local<Function> Boolean_7 = Local<Function>::Cast(global_6->Get(String::NewFromUtf8(isolate,
"Boolean"))); Local<Context> ctx_5 = isolate->GetCurrentContext();
...
Local<Value> result_13 = Boolean_7->Call(Null(isolate), 1, argv_12);
if (result_13->ToBoolean()->Value()) {
// return a;
args.GetReturnValue().Set(a_2);
return;
}
Challenges: Rust
● First time writing it 🤦
○ Borrow checker took a while
○ But JavaScripters would love the syntax
○ Didn’t make use of Traits but they are super expressive
● Parser frontend library wasn’t super mature
● Parser frontend library wasn’t TypeScript/Flow
○ Limits specializing code generation
Challenges: V8 documentation
● Better than expected!
● Not a ton of people writing/documenting
○ How to array literal?
○ How to std::string -> V8::String, vice-versa?
● What is built-in vs. not?
○ E.g. Value::Equals, Value::StrictEquals, String::Concat
○ But no Value::Add, Number::Add
Frustrated by...
● Lack of Rust knowledge
● No Rust TypeScript parser
● Bad design of code generator
Jsc v0.5
● Proof-of-concept TypeScript compiler
○ Written in TypeScript, uses the TypeScript compiler API
● Targets native Node addons in C++
○ Uses node-gyp
● Uses a 1-line entrypoint to load and run the addon
Two major changes for generated code quality
1. Destination-driven code generation
2. Basic type awareness
1. Destination-driven code generation
● By Kent Dybvig at Cisco for Chez Scheme
● Parents pass destination of output to child
● Easy to implement
● Highly space-efficient
● Single-pass
● Adapted by V8 team
2. Basic type awareness
● Taking advantage of obvious type information
○ Leaf-type propagation only
● Not even tapping TypeScript yet
Supported functionality
● Function declarations and function calls
● Basic tail-call optimization
● Var declarations
● Few primitive operators
● Number, string, boolean and null literals
● Access to Node builtins via `global`
● Static imports
Unsupported functionality
● Specialized (unboxed) functions
● Prototype functions/nested functions/closures
● Whole ton of other stuff
Example
function fib(n, a, b) {
if (n == 0) { return a; }
if (n == 1) { return b; }
return fib(n - 1, b, a + b);
}
function main() {
console.log(fib(50, 0, 1));
}
Example cont.
$ node ./build/jsc.js fib.js
$ cat bin/index.js
require("build/Release/fib.node").jsc_main()
$ node bin/index.js
12586269025
Generated code
https://github.com/eatonphil/jsc#code-produced
Analysis: the good
● It works!
● DDCG & type propagation seriously reduce bloat
○ Down to 30 LOC C++
● Better boolean checks
○ Local<Boolean> sym_anon_9 = args[0]->StrictEquals(sym_rhs_11) ? True(isolate) : False(isolate);
if (sym_anon_9->IsTrue()) {
● Complexity of common operations hidden by inline functions (in lib.cc)
○ Local<Value> sym_arg_17 = genericMinus(isolate, args[0], sym_rhs_19);
Local<Value> sym_arg_21 = genericPlus(isolate, args[1], args[2]);
Analysis: the bad
● What’s with copying args on every function?
○ Isolate* isolate = _args.GetIsolate();
std::vector<Local<Value>> args(_args.Length());;
for (int i = 0; i < _args.Length(); i++) args[i] = _args[i];
● Regression: no source-to-source commenting
● Reduced syntax support in TypeScript port
● Tracking types increases complexity of the compiler
Challenges: TypeScript API documentation
● Better than expected
● Could use more!
● E.g. behavior of createProgram and getSourceFiles???
Performance?
● Trivial benchmarks only (e.g. fib)
○ Numbers not worth sharing
● First iteration non-TCO was awful
● First iteration TCO was on par with Node
● Second iteration TCO and non-TCO on par with Node
○ Not sure why…
● Need to build out syntax support for more complex microbenchmarks
○ MD5, SHA-1, N Queens etc.
What next?
● More syntax support
● Measuring binary size
● Performance benchmarking
● Specialized (unboxed) blocks
● Seamless FFI (embedded C++?)
● Tree-shaking
● Self-hosting
● Own (Node API-compatible) runtime?
● Blogging about ^^^
Links
● JSC source
● V8 library documentation
● Basic TypeScript compiler API guide
● TypeScript Compiler types source
● Node addon guide
● Node-gyp
Questions?
Thank you!

Más contenido relacionado

La actualidad más candente

IL2CPP: Debugging and Profiling
IL2CPP: Debugging and ProfilingIL2CPP: Debugging and Profiling
IL2CPP: Debugging and Profilingjoncham
 
Introduction to Go programming
Introduction to Go programmingIntroduction to Go programming
Introduction to Go programmingExotel
 
[COSCUP 2020] How to use llvm frontend library-libtooling
[COSCUP 2020] How to use llvm frontend library-libtooling[COSCUP 2020] How to use llvm frontend library-libtooling
[COSCUP 2020] How to use llvm frontend library-libtoolingDouglas Chen
 
Clang Analyzer Tool Review
Clang Analyzer Tool ReviewClang Analyzer Tool Review
Clang Analyzer Tool ReviewDoug Schuster
 
Oh the compilers you'll build
Oh the compilers you'll buildOh the compilers you'll build
Oh the compilers you'll buildMark Stoodley
 
Connecting C++ and JavaScript on the Web with Embind
Connecting C++ and JavaScript on the Web with EmbindConnecting C++ and JavaScript on the Web with Embind
Connecting C++ and JavaScript on the Web with EmbindChad Austin
 
Android Developer Days: Increasing performance of big arrays processing on An...
Android Developer Days: Increasing performance of big arrays processing on An...Android Developer Days: Increasing performance of big arrays processing on An...
Android Developer Days: Increasing performance of big arrays processing on An...Stanfy
 
Elixir + GraphQL = Absinthe 2019.04.10
Elixir + GraphQL = Absinthe 2019.04.10Elixir + GraphQL = Absinthe 2019.04.10
Elixir + GraphQL = Absinthe 2019.04.10Alexander Knowles
 
freeCodeCamp Tokyo Meetup #18
freeCodeCamp Tokyo Meetup #18freeCodeCamp Tokyo Meetup #18
freeCodeCamp Tokyo Meetup #18健太 田上
 
Code for kombol - Objects and Functions in JS and NodeJS
Code for kombol - Objects and Functions in JS and NodeJSCode for kombol - Objects and Functions in JS and NodeJS
Code for kombol - Objects and Functions in JS and NodeJSRiyadh Al Nur
 
Partial Continuations, Lessons From JavaScript and Guile in 2012 (Quasiconf 2...
Partial Continuations, Lessons From JavaScript and Guile in 2012 (Quasiconf 2...Partial Continuations, Lessons From JavaScript and Guile in 2012 (Quasiconf 2...
Partial Continuations, Lessons From JavaScript and Guile in 2012 (Quasiconf 2...Igalia
 
C++ in kernel mode
C++ in kernel modeC++ in kernel mode
C++ in kernel modecorehard_by
 
Kyrylo Cherneha "C++ & Python Interaction in Automotive Industry"
Kyrylo Cherneha "C++ & Python Interaction in Automotive Industry"Kyrylo Cherneha "C++ & Python Interaction in Automotive Industry"
Kyrylo Cherneha "C++ & Python Interaction in Automotive Industry"LogeekNightUkraine
 
IDE as a Front-end and Fast time-to-market language support in Eclipse IDE re...
IDE as a Front-end and Fast time-to-market language support in Eclipse IDE re...IDE as a Front-end and Fast time-to-market language support in Eclipse IDE re...
IDE as a Front-end and Fast time-to-market language support in Eclipse IDE re...Mickael Istria
 
.NET Foundation, Future of .NET and C#
.NET Foundation, Future of .NET and C#.NET Foundation, Future of .NET and C#
.NET Foundation, Future of .NET and C#Bertrand Le Roy
 
Using Aspects for Language Portability (SCAM 2010)
Using Aspects for Language Portability (SCAM 2010)Using Aspects for Language Portability (SCAM 2010)
Using Aspects for Language Portability (SCAM 2010)lennartkats
 

La actualidad más candente (20)

IL2CPP: Debugging and Profiling
IL2CPP: Debugging and ProfilingIL2CPP: Debugging and Profiling
IL2CPP: Debugging and Profiling
 
Introduction to Go programming
Introduction to Go programmingIntroduction to Go programming
Introduction to Go programming
 
[COSCUP 2020] How to use llvm frontend library-libtooling
[COSCUP 2020] How to use llvm frontend library-libtooling[COSCUP 2020] How to use llvm frontend library-libtooling
[COSCUP 2020] How to use llvm frontend library-libtooling
 
Clang Analyzer Tool Review
Clang Analyzer Tool ReviewClang Analyzer Tool Review
Clang Analyzer Tool Review
 
Golang
GolangGolang
Golang
 
Oh the compilers you'll build
Oh the compilers you'll buildOh the compilers you'll build
Oh the compilers you'll build
 
Connecting C++ and JavaScript on the Web with Embind
Connecting C++ and JavaScript on the Web with EmbindConnecting C++ and JavaScript on the Web with Embind
Connecting C++ and JavaScript on the Web with Embind
 
Android Developer Days: Increasing performance of big arrays processing on An...
Android Developer Days: Increasing performance of big arrays processing on An...Android Developer Days: Increasing performance of big arrays processing on An...
Android Developer Days: Increasing performance of big arrays processing on An...
 
Elixir + GraphQL = Absinthe 2019.04.10
Elixir + GraphQL = Absinthe 2019.04.10Elixir + GraphQL = Absinthe 2019.04.10
Elixir + GraphQL = Absinthe 2019.04.10
 
freeCodeCamp Tokyo Meetup #18
freeCodeCamp Tokyo Meetup #18freeCodeCamp Tokyo Meetup #18
freeCodeCamp Tokyo Meetup #18
 
Code for kombol - Objects and Functions in JS and NodeJS
Code for kombol - Objects and Functions in JS and NodeJSCode for kombol - Objects and Functions in JS and NodeJS
Code for kombol - Objects and Functions in JS and NodeJS
 
Partial Continuations, Lessons From JavaScript and Guile in 2012 (Quasiconf 2...
Partial Continuations, Lessons From JavaScript and Guile in 2012 (Quasiconf 2...Partial Continuations, Lessons From JavaScript and Guile in 2012 (Quasiconf 2...
Partial Continuations, Lessons From JavaScript and Guile in 2012 (Quasiconf 2...
 
Intro dotnet
Intro dotnetIntro dotnet
Intro dotnet
 
C++ in kernel mode
C++ in kernel modeC++ in kernel mode
C++ in kernel mode
 
Kyrylo Cherneha "C++ & Python Interaction in Automotive Industry"
Kyrylo Cherneha "C++ & Python Interaction in Automotive Industry"Kyrylo Cherneha "C++ & Python Interaction in Automotive Industry"
Kyrylo Cherneha "C++ & Python Interaction in Automotive Industry"
 
Golang
GolangGolang
Golang
 
IDE as a Front-end and Fast time-to-market language support in Eclipse IDE re...
IDE as a Front-end and Fast time-to-market language support in Eclipse IDE re...IDE as a Front-end and Fast time-to-market language support in Eclipse IDE re...
IDE as a Front-end and Fast time-to-market language support in Eclipse IDE re...
 
An Introduction to PyPy
An Introduction to PyPyAn Introduction to PyPy
An Introduction to PyPy
 
.NET Foundation, Future of .NET and C#
.NET Foundation, Future of .NET and C#.NET Foundation, Future of .NET and C#
.NET Foundation, Future of .NET and C#
 
Using Aspects for Language Portability (SCAM 2010)
Using Aspects for Language Portability (SCAM 2010)Using Aspects for Language Portability (SCAM 2010)
Using Aspects for Language Portability (SCAM 2010)
 

Similar a AOT-compilation of JavaScript with V8

Mender.io | Develop embedded applications faster | Comparing C and Golang
Mender.io | Develop embedded applications faster | Comparing C and GolangMender.io | Develop embedded applications faster | Comparing C and Golang
Mender.io | Develop embedded applications faster | Comparing C and GolangMender.io
 
Creating a reasonable project boilerplate
Creating a reasonable project boilerplateCreating a reasonable project boilerplate
Creating a reasonable project boilerplateStanislav Petrov
 
Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016maiktoepfer
 
10 reasons to be excited about go
10 reasons to be excited about go10 reasons to be excited about go
10 reasons to be excited about goDvir Volk
 
How to contribute textual tooling for apache camel in several id es
How to contribute textual tooling for apache camel in several id esHow to contribute textual tooling for apache camel in several id es
How to contribute textual tooling for apache camel in several id esAurélien Pupier
 
Compiler design notes phases of compiler
Compiler design notes phases of compilerCompiler design notes phases of compiler
Compiler design notes phases of compilerovidlivi91
 
Dmytro Dziubenko "Developer's toolchain"
Dmytro Dziubenko "Developer's toolchain"Dmytro Dziubenko "Developer's toolchain"
Dmytro Dziubenko "Developer's toolchain"Fwdays
 
Continuous integration is not a solved problem
Continuous integration is not a solved problemContinuous integration is not a solved problem
Continuous integration is not a solved problemKristian Van Der Vliet
 
[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...
[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...
[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...Sang Don Kim
 
Making CLIs with Node.js
Making CLIs with Node.jsMaking CLIs with Node.js
Making CLIs with Node.jsJoseph Lust
 
Python and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthroughPython and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthroughgabriellekuruvilla
 
Implementing OpenCL support in GEGL and GIMP
Implementing OpenCL support in GEGL and GIMPImplementing OpenCL support in GEGL and GIMP
Implementing OpenCL support in GEGL and GIMPlgworld
 
Dart the better Javascript 2015
Dart the better Javascript 2015Dart the better Javascript 2015
Dart the better Javascript 2015Jorg Janke
 
Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015
Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015
Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015Windows Developer
 
Python for PHP developers
Python for PHP developersPython for PHP developers
Python for PHP developersbennuttall
 
SFScon18 - Gerhard Sulzberger - Jason Tevnan - gitops with gitlab + terraform
SFScon18 - Gerhard Sulzberger - Jason Tevnan  - gitops with gitlab + terraformSFScon18 - Gerhard Sulzberger - Jason Tevnan  - gitops with gitlab + terraform
SFScon18 - Gerhard Sulzberger - Jason Tevnan - gitops with gitlab + terraformSouth Tyrol Free Software Conference
 

Similar a AOT-compilation of JavaScript with V8 (20)

Mender.io | Develop embedded applications faster | Comparing C and Golang
Mender.io | Develop embedded applications faster | Comparing C and GolangMender.io | Develop embedded applications faster | Comparing C and Golang
Mender.io | Develop embedded applications faster | Comparing C and Golang
 
Creating a reasonable project boilerplate
Creating a reasonable project boilerplateCreating a reasonable project boilerplate
Creating a reasonable project boilerplate
 
Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016
 
Paris.py
Paris.pyParis.py
Paris.py
 
10 reasons to be excited about go
10 reasons to be excited about go10 reasons to be excited about go
10 reasons to be excited about go
 
How to contribute textual tooling for apache camel in several id es
How to contribute textual tooling for apache camel in several id esHow to contribute textual tooling for apache camel in several id es
How to contribute textual tooling for apache camel in several id es
 
Compiler design notes phases of compiler
Compiler design notes phases of compilerCompiler design notes phases of compiler
Compiler design notes phases of compiler
 
Dmytro Dziubenko "Developer's toolchain"
Dmytro Dziubenko "Developer's toolchain"Dmytro Dziubenko "Developer's toolchain"
Dmytro Dziubenko "Developer's toolchain"
 
Continuous integration is not a solved problem
Continuous integration is not a solved problemContinuous integration is not a solved problem
Continuous integration is not a solved problem
 
[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...
[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...
[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...
 
Making CLIs with Node.js
Making CLIs with Node.jsMaking CLIs with Node.js
Making CLIs with Node.js
 
Transitioning to Native
Transitioning to NativeTransitioning to Native
Transitioning to Native
 
Ruxmon.2013-08.-.CodeBro!
Ruxmon.2013-08.-.CodeBro!Ruxmon.2013-08.-.CodeBro!
Ruxmon.2013-08.-.CodeBro!
 
Python and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthroughPython and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthrough
 
Implementing OpenCL support in GEGL and GIMP
Implementing OpenCL support in GEGL and GIMPImplementing OpenCL support in GEGL and GIMP
Implementing OpenCL support in GEGL and GIMP
 
Dart the better Javascript 2015
Dart the better Javascript 2015Dart the better Javascript 2015
Dart the better Javascript 2015
 
Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015
Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015
Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015
 
Python for PHP developers
Python for PHP developersPython for PHP developers
Python for PHP developers
 
Rusty Python
Rusty PythonRusty Python
Rusty Python
 
SFScon18 - Gerhard Sulzberger - Jason Tevnan - gitops with gitlab + terraform
SFScon18 - Gerhard Sulzberger - Jason Tevnan  - gitops with gitlab + terraformSFScon18 - Gerhard Sulzberger - Jason Tevnan  - gitops with gitlab + terraform
SFScon18 - Gerhard Sulzberger - Jason Tevnan - gitops with gitlab + terraform
 

Último

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 

Último (20)

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 

AOT-compilation of JavaScript with V8

  • 1. AOT-compilation with V8 Phil Eaton Engineer & Manager at Capsule8 notes.eatonphil.com @phil_eaton
  • 2. Dynamic languages == interpreter?
  • 3. Lots of dynamic languages have AOT compilers! ● And produce native binaries ● Python -> Cython ● Java -> Graal ● Common Lisp -> SBCL ● Scheme -> Chicken Scheme
  • 4. Static types & Compilation
  • 5. Case study: Cython ● Compiles Python to C using libpython ● Produces a single binary ● Simple FFI ○ Though not as simple as Chicken Scheme ● Superset of Python ○ Pure Python: OK ○ Optional types for more efficient code: OK
  • 6. Me vs. team of PhDs over years? Not really trying to compete on speed
  • 7. AOT-compilation can help any language ● Simplify deployment & packaging ● Simplify FFIs ● Make performance more predictable ○ Compared to JIT interpreters
  • 8. AOT-compilation and dynamic languages cont. ● With additional sacrifices to dynamism e.g.: ○ No dynamic imports ○ Optional types ● Can get: ○ Relatively efficiently generated code with little effort ○ Smaller binaries/output
  • 9. My background ● Working on a Scheme interpreter in 2017 ● Wanted to add a compiler backend ● Process made trivial by using ○ Existing parser ○ Interpreter runtime as a library
  • 10. Realized this is how (e.g.) Cython works...
  • 11. Nothing like this exists for JavaScript That I know of 3rd party JavaScript parser Source code AST Fancy new compiler C++ & V8 Final product: Native code
  • 13. Jsc v0 ● Proof-of-concept ES5 compiler ○ Written in Rust, uses an existing ES5 parser frontend ● Targets native Node addons in C++ ○ Uses node-gyp ● Uses a 1-line entrypoint to load and run the addon ● Completely type unaware ○ Not even leaf-type propagation
  • 14. Supported functionality ● Functions and function calls ● Basic tail-call optimization ● Var declarations ● Many primitive operators ● Object, array, number, string, boolean and null literals ● Access to Node builtins via `global` ● Basic source-to-source comments for debugging generated output
  • 15. Unsupported functionality ● Specialized functions ● Imports ● Prototype functions/nested functions/closures ● Whole bunch of other stuff
  • 16. Example function fib(n, a, b) { if (n == 0) { return a; } if (n == 1) { return b; } return fib(n - 1, b, a + b); } function main() { console.log(fib(50, 0, 1)); }
  • 17. Example cont. $ jsc fib.js $ cat build/fib.js require("build/Release/fib.node").jsc_main() $ node build/fib.js 12586269025
  • 19.
  • 20. Analysis: the good ● It works! ● V8 makes compiling to C++ dead simple! ○ Object representation: V8! ■ String::NewFromUtf8(isolate, "Boolean") ■ Number::New(isolate, 0) ○ Memory management: V8! ● Source-to-source commenting is helpful ○ // return a; args.GetReturnValue().Set(a_2); return;
  • 21. Analysis: the bad ● Relatively bloated code ○ 5 LOC JavaScript -> 54 LOC C++ ● TONS of redundant casting, moves ● What is going on with the Boolean check??? ○ Local<Context> ctx_5 = isolate->GetCurrentContext(); Local<Object> global_6 = ctx_5->Global(); Local<Function> Boolean_7 = Local<Function>::Cast(global_6->Get(String::NewFromUtf8(isolate, "Boolean"))); Local<Context> ctx_5 = isolate->GetCurrentContext(); ... Local<Value> result_13 = Boolean_7->Call(Null(isolate), 1, argv_12); if (result_13->ToBoolean()->Value()) { // return a; args.GetReturnValue().Set(a_2); return; }
  • 22. Challenges: Rust ● First time writing it 🤦 ○ Borrow checker took a while ○ But JavaScripters would love the syntax ○ Didn’t make use of Traits but they are super expressive ● Parser frontend library wasn’t super mature ● Parser frontend library wasn’t TypeScript/Flow ○ Limits specializing code generation
  • 23. Challenges: V8 documentation ● Better than expected! ● Not a ton of people writing/documenting ○ How to array literal? ○ How to std::string -> V8::String, vice-versa? ● What is built-in vs. not? ○ E.g. Value::Equals, Value::StrictEquals, String::Concat ○ But no Value::Add, Number::Add
  • 24. Frustrated by... ● Lack of Rust knowledge ● No Rust TypeScript parser ● Bad design of code generator
  • 25. Jsc v0.5 ● Proof-of-concept TypeScript compiler ○ Written in TypeScript, uses the TypeScript compiler API ● Targets native Node addons in C++ ○ Uses node-gyp ● Uses a 1-line entrypoint to load and run the addon
  • 26. Two major changes for generated code quality 1. Destination-driven code generation 2. Basic type awareness
  • 27. 1. Destination-driven code generation ● By Kent Dybvig at Cisco for Chez Scheme ● Parents pass destination of output to child ● Easy to implement ● Highly space-efficient ● Single-pass ● Adapted by V8 team
  • 28. 2. Basic type awareness ● Taking advantage of obvious type information ○ Leaf-type propagation only ● Not even tapping TypeScript yet
  • 29. Supported functionality ● Function declarations and function calls ● Basic tail-call optimization ● Var declarations ● Few primitive operators ● Number, string, boolean and null literals ● Access to Node builtins via `global` ● Static imports
  • 30. Unsupported functionality ● Specialized (unboxed) functions ● Prototype functions/nested functions/closures ● Whole ton of other stuff
  • 31. Example function fib(n, a, b) { if (n == 0) { return a; } if (n == 1) { return b; } return fib(n - 1, b, a + b); } function main() { console.log(fib(50, 0, 1)); }
  • 32. Example cont. $ node ./build/jsc.js fib.js $ cat bin/index.js require("build/Release/fib.node").jsc_main() $ node bin/index.js 12586269025
  • 34.
  • 35. Analysis: the good ● It works! ● DDCG & type propagation seriously reduce bloat ○ Down to 30 LOC C++ ● Better boolean checks ○ Local<Boolean> sym_anon_9 = args[0]->StrictEquals(sym_rhs_11) ? True(isolate) : False(isolate); if (sym_anon_9->IsTrue()) { ● Complexity of common operations hidden by inline functions (in lib.cc) ○ Local<Value> sym_arg_17 = genericMinus(isolate, args[0], sym_rhs_19); Local<Value> sym_arg_21 = genericPlus(isolate, args[1], args[2]);
  • 36. Analysis: the bad ● What’s with copying args on every function? ○ Isolate* isolate = _args.GetIsolate(); std::vector<Local<Value>> args(_args.Length());; for (int i = 0; i < _args.Length(); i++) args[i] = _args[i]; ● Regression: no source-to-source commenting ● Reduced syntax support in TypeScript port ● Tracking types increases complexity of the compiler
  • 37. Challenges: TypeScript API documentation ● Better than expected ● Could use more! ● E.g. behavior of createProgram and getSourceFiles???
  • 38. Performance? ● Trivial benchmarks only (e.g. fib) ○ Numbers not worth sharing ● First iteration non-TCO was awful ● First iteration TCO was on par with Node ● Second iteration TCO and non-TCO on par with Node ○ Not sure why… ● Need to build out syntax support for more complex microbenchmarks ○ MD5, SHA-1, N Queens etc.
  • 39. What next? ● More syntax support ● Measuring binary size ● Performance benchmarking ● Specialized (unboxed) blocks ● Seamless FFI (embedded C++?) ● Tree-shaking ● Self-hosting ● Own (Node API-compatible) runtime? ● Blogging about ^^^
  • 40. Links ● JSC source ● V8 library documentation ● Basic TypeScript compiler API guide ● TypeScript Compiler types source ● Node addon guide ● Node-gyp