SlideShare una empresa de Scribd logo
1 de 40
Descargar para leer sin conexión
Statically Compiling
Ruby with LLVM
Laurent Sansonetti
HipByte
About me
•

Laurent Sansonetti
•

Programming Language Nerd

•

Founder of HipByte

•

From Belgium (yay!)
MacRuby
MacRuby
•

2007: Project created (as a hobby)
•

Replacement for RubyCocoa

•

Fork of CRuby 1.9

•

2008: Had a beer with Chris Lattner

•

2009: Replaced bytecode VM by LLVM JIT

•

2011: Left Apple
RubyMotion
RubyMotion
•

Command-line toolchain for iOS / OS X dev

•

Implementation of Ruby dialect

•

Unified Ruby runtime with Objective-C

•

Static compiler for Ruby into Intel/ARM

•

Platform for wrappers/libraries ecosystem

•

Commercial product & sustainable business
RubyMotion
•

Command-line toolchain for iOS / OS X dev

•

Implementation of Ruby dialect

•

Unified Ruby runtime with Objective-C

•

Static compiler for Ruby into Intel/ARM

•

Platform for wrappers/libraries ecosystem

•

Commercial product & sustainable business
Ruby
Ruby
•

Created in 1995 by Yukihiro Matsumoto (Matz)
•

“human-oriented language”

•

Dynamically typed

•

Object oriented

•

Blocks

•

Exceptions

•

Garbage collection

•

…
hello.rb
class Hello
def initialize(something)
@something = something
end
def say
puts “Hello “ + @something
end
end
!

Hello.new(‘world’).say
CRuby
Compilation

Ruby Code

AST
Bytecode

Runtime
Let’s use LLVM!
RubyMotion
Compilation

Ruby Code

AST
LLVM IR
Assembly
Runtime
RubyMotion compiler
•

About 12k C++ LOC

•

Targets LLVM 2.4

•

Supports the entire Ruby language “specifications”
File functions
class Hello
def initialize(something)
…
end
def say
…
end
end
!

class Ohai < Hello
def say
…
end
end
!

Hello.new(‘world’).say

File Scope
1

5
3

Hello
Ctor
2

Hello
Scope

Ohai
Ctor
4

Ohai
Scope

File
Code
Method functions
class Hello
…
def say
puts “Hello “ + @something
end
end

Method
IMP

Ruby Runtime

ObjC
Stub

ObjC Runtime
Methods
def hello(x, y, z)
…
end
Methods
define internal i32 @"rb_scope__hello:__"(i32 %self,
i8* %sel, i32 %a, i32 %b, i32 %c) {
MainBlock:
…
}
Conditionals
def hello(something)
if something
true
else
false
end
end
Conditionals
define internal i32 @"rb_scope__hello:__"(i32 %self, i8* %sel, i32 %something) {
MainBlock:
call void @llvm.dbg.declare(metadata !{i32 %self}, metadata !23), !dbg !54
call void @llvm.dbg.value(metadata !{i32 %something}, i64 0, metadata !24), !dbg !54
%0 = alloca i8
store volatile i8 0, i8* %0
switch i32 %something, label %merge [
i32 0, label %else
i32 4, label %else
]

!

else:
br label %merge

!

; preds = %MainBlock, %MainBlock

merge:
; preds = %MainBlock, %else
%iftmp = phi i32 [ 0, %else ], [ 2, %MainBlock ]
ret i32 %iftmp
}
Local variables
•

Allocated on the stack
•

Benefits from the mem2reg pass
Block variables
•

Allocated initially on the stack

•

Re-allocated in heap memory in case the block
leaves the scope of the method
kernel.bc
•

Runtime primitives
•

vm_fast_{plus,minus,…} (arithmetic ops)

•

vm_ivar_{get,set} (instance variables)

•

vm_dispatch (method dispatch)

•

…

•

Pre-compiled into LLVM bitcode

•

Loaded by the compiler
•

Provides the initial module
Instance variables
def initialize(foo)
@foo = foo
end
Instance variables
define internal i32 @"rb_scope__initialize:__"(i32 %self, i8* %sel, i32 %foo) {
MainBlock:
%0 = alloca i32*
%1 = alloca i32
store i32* %1, i32** %0
store i32 %foo, i32* %1
%2 = alloca i8
store volatile i8 0, i8* %2
br label %entry_point
!
entry_point:
%3 = load i32** %0
%4 = load i32* %3
%5 = load i32* @3
%6 = load i8** @4
call void @vm_ivar_set(i32 %self, i32 %5, i32 %4, i8* %6)
ret i32 %4
}
Instance variables
PRIMITIVE void
vm_ivar_set(VALUE obj, ID name, VALUE val, void *cache_p)
{
…
klass = *(VALUE *)obj;
if (klass == cache->klass) {
if ((unsigned int)cache->slot < ROBJECT(obj)->num_slots) {
rb_object_ivar_slot_t *slot;
slot = &ROBJECT(obj)->slots[cache->slot];
if (slot->name == name) {
…
GC_WB_OBJ(&slot->value, val);
return;
…
// slow path
PRIMITIVE VALUE
vm_gc_wb(VALUE *slot, VALUE val)
{
…
*slot = val;
return val;
}
After passes
Instance variables
define internal i32 @"rb_scope__initialize:__"(i32 %self, i8* %sel, i32 %foo) {
MainBlock:
br label %entry_point
!
entry_point:
…
%39 = getelementptr inbounds %struct.rb_object_ivar_slot_t* %28, i32 %26,
i32 1
store i32 %4, i32* %39
…
ret i32 %4
}
Arithmetic
def answer
21 + 21
end
Arithmetic
define internal i32 @rb_scope__answer__(i32 %self, i8* %sel) {
MainBlock:
br label %entry_point
!

entry_point:
%0 = load i8** @8
%1 = load i8* @9
%2 = call i32 @vm_fast_plus(i32 85, i32 85, i8 %1)
ret i32 %2
}
Arithmetic
PRIMITIVE VALUE
vm_fast_plus(VALUE left, VALUE right, unsigned char overridden)
{
if (overridden == 0 && NUMERIC_P(left) && NUMERIC_P(right)) {
if (FIXNUM_P(left) && FIXNUM_P(right)) {
const long res = FIX2LONG(left) + FIX2LONG(right);
if (FIXABLE(res)) {
return LONG2FIX(res);
}
}
}
… // slow path
}
After passes
Arithmetic
define internal i32 @rb_scope__answer__(i32 %self, i8* %sel) {
MainBlock:
br label %entry_point
!

entry_point:
…
ret i32 169
}
Exceptions
•

Implemented as C++ exceptions

•

Zero-cost for “normal flow”

•

Handlers are compiled using IR intrinsics
•

•

“catch all” landing pad clause

Exception#raise triggers __cxa_raise()
DWARF
•

All instructions have proper debug location
metadata

•

Method/block arguments and local variables are
tagged as DW_TAG_{arg,auto}_variable

•

Build system generates a .dSYM bundle
•

Can be loaded by gdb/lldb, atos(1), profilers, etc.
REPL
•

Allows to interpret expressions at runtime
•

Only for development (simulator)

•

App process loads the compiler

•

Uses JIT execution engine
Demo
LLVM lessons
Pluses
• Great to write static
compilers
• Easy to target new
platforms
• Lots of great
optimization passes

Minuses
• C++ API breakage
• Huge code size
• IR is not 100% portable
• Proprietary backends
• Not as great to use as a JIT
LLVM is awesome!
Thank you
lrz@hipbyte.com
Twitter: @lrz

Más contenido relacionado

La actualidad más candente

Introduction to .net
Introduction to .netIntroduction to .net
Introduction to .net
Naveen Sihag
 
Seminar: CoinMP - Open Source Solver - Nov 2011
Seminar: CoinMP - Open Source Solver - Nov 2011Seminar: CoinMP - Open Source Solver - Nov 2011
Seminar: CoinMP - Open Source Solver - Nov 2011
Bjarni Kristjánsson
 

La actualidad más candente (18)

Introduction to .net
Introduction to .netIntroduction to .net
Introduction to .net
 
A deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio moduleA deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio module
 
One Shellcode to Rule Them All: Cross-Platform Exploitation
One Shellcode to Rule Them All: Cross-Platform ExploitationOne Shellcode to Rule Them All: Cross-Platform Exploitation
One Shellcode to Rule Them All: Cross-Platform Exploitation
 
Automatic Reference Counting @ Pragma Night
Automatic Reference Counting @ Pragma NightAutomatic Reference Counting @ Pragma Night
Automatic Reference Counting @ Pragma Night
 
Modern Objective-C @ Pragma Night
Modern Objective-C @ Pragma NightModern Objective-C @ Pragma Night
Modern Objective-C @ Pragma Night
 
Seminar: CoinMP - Open Source Solver - Nov 2011
Seminar: CoinMP - Open Source Solver - Nov 2011Seminar: CoinMP - Open Source Solver - Nov 2011
Seminar: CoinMP - Open Source Solver - Nov 2011
 
Talk: The Present and Future of Pharo
Talk: The Present and Future of PharoTalk: The Present and Future of Pharo
Talk: The Present and Future of Pharo
 
Denker - Pharo: Present and Future - 2009-07-14
Denker - Pharo: Present and Future - 2009-07-14Denker - Pharo: Present and Future - 2009-07-14
Denker - Pharo: Present and Future - 2009-07-14
 
Operating Systems - A Primer
Operating Systems - A PrimerOperating Systems - A Primer
Operating Systems - A Primer
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016
 
Android RenderScript on LLVM
Android RenderScript on LLVMAndroid RenderScript on LLVM
Android RenderScript on LLVM
 
asyncio internals
asyncio internalsasyncio internals
asyncio internals
 
Handling inline assembly in Clang and LLVM
Handling inline assembly in Clang and LLVMHandling inline assembly in Clang and LLVM
Handling inline assembly in Clang and LLVM
 
Kotlin
KotlinKotlin
Kotlin
 
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
 
Dataflow: Declarative concurrency in Ruby
Dataflow: Declarative concurrency in RubyDataflow: Declarative concurrency in Ruby
Dataflow: Declarative concurrency in Ruby
 
Javascript ES6
Javascript ES6Javascript ES6
Javascript ES6
 
Swift core
Swift coreSwift core
Swift core
 

Destacado

Destacado (16)

Accelerating Ruby with LLVM
Accelerating Ruby with LLVMAccelerating Ruby with LLVM
Accelerating Ruby with LLVM
 
Predlog ministara (biografije), Vlada Srbije
Predlog ministara (biografije), Vlada SrbijePredlog ministara (biografije), Vlada Srbije
Predlog ministara (biografije), Vlada Srbije
 
Els Oosthoek, artikel TVOO 2017 Nick van Dam
Els Oosthoek, artikel TVOO 2017 Nick van Dam Els Oosthoek, artikel TVOO 2017 Nick van Dam
Els Oosthoek, artikel TVOO 2017 Nick van Dam
 
Design and Development Solution
Design and Development SolutionDesign and Development Solution
Design and Development Solution
 
Teach children-basics
Teach children-basicsTeach children-basics
Teach children-basics
 
Simmethod From Software As A Service To Outcomes As A Service, Twitter and Ya...
Simmethod From Software As A Service To Outcomes As A Service, Twitter and Ya...Simmethod From Software As A Service To Outcomes As A Service, Twitter and Ya...
Simmethod From Software As A Service To Outcomes As A Service, Twitter and Ya...
 
【土曜会】ハードコアな鑑賞入門:カワムラシュウイチ
【土曜会】ハードコアな鑑賞入門:カワムラシュウイチ【土曜会】ハードコアな鑑賞入門:カワムラシュウイチ
【土曜会】ハードコアな鑑賞入門:カワムラシュウイチ
 
Blog links-url-content efg
Blog links-url-content efgBlog links-url-content efg
Blog links-url-content efg
 
Le performance
Le performanceLe performance
Le performance
 
Brillo/Weave Part 1: High Level Introduction
Brillo/Weave Part 1: High Level IntroductionBrillo/Weave Part 1: High Level Introduction
Brillo/Weave Part 1: High Level Introduction
 
10 Social Sharing Statistics
10 Social Sharing Statistics10 Social Sharing Statistics
10 Social Sharing Statistics
 
Melhores Negócios com o Office365
Melhores Negócios com o Office365Melhores Negócios com o Office365
Melhores Negócios com o Office365
 
Presentación escuela SEC/FEC de paciente experto. Organizada por Mimocardio
Presentación escuela SEC/FEC de paciente experto. Organizada por MimocardioPresentación escuela SEC/FEC de paciente experto. Organizada por Mimocardio
Presentación escuela SEC/FEC de paciente experto. Organizada por Mimocardio
 
Blind wijnproeven nigtevecht 3 maart 2017
Blind wijnproeven nigtevecht 3 maart 2017Blind wijnproeven nigtevecht 3 maart 2017
Blind wijnproeven nigtevecht 3 maart 2017
 
Redefining manhood
Redefining manhoodRedefining manhood
Redefining manhood
 
Re-thinking the Organization for Agility
Re-thinking the Organization for Agility Re-thinking the Organization for Agility
Re-thinking the Organization for Agility
 

Similar a Statically Compiling Ruby with LLVM

Memory Management with Java and C++
Memory Management with Java and C++Memory Management with Java and C++
Memory Management with Java and C++
Mohammad Shaker
 
Javascript engine performance
Javascript engine performanceJavascript engine performance
Javascript engine performance
Duoyi Wu
 
Using Smalltalk for controlling robotics systems
Using Smalltalk for controlling robotics systemsUsing Smalltalk for controlling robotics systems
Using Smalltalk for controlling robotics systems
Serge Stinckwich
 

Similar a Statically Compiling Ruby with LLVM (20)

Gcrc talk
Gcrc talkGcrc talk
Gcrc talk
 
Bypassing ASLR Exploiting CVE 2015-7545
Bypassing ASLR Exploiting CVE 2015-7545Bypassing ASLR Exploiting CVE 2015-7545
Bypassing ASLR Exploiting CVE 2015-7545
 
Introduction to c part -3
Introduction to c   part -3Introduction to c   part -3
Introduction to c part -3
 
What has to be paid attention when reviewing code of the library you develop
What has to be paid attention when reviewing code of the library you developWhat has to be paid attention when reviewing code of the library you develop
What has to be paid attention when reviewing code of the library you develop
 
Memory Management with Java and C++
Memory Management with Java and C++Memory Management with Java and C++
Memory Management with Java and C++
 
Synchronously call your async functions
Synchronously call your async functionsSynchronously call your async functions
Synchronously call your async functions
 
Javascript engine performance
Javascript engine performanceJavascript engine performance
Javascript engine performance
 
Bypassing DEP using ROP
Bypassing DEP using ROPBypassing DEP using ROP
Bypassing DEP using ROP
 
Jit builder status and directions 2018 03-28
Jit builder status and directions 2018 03-28Jit builder status and directions 2018 03-28
Jit builder status and directions 2018 03-28
 
0100_Embeded_C_CompilationProcess.pdf
0100_Embeded_C_CompilationProcess.pdf0100_Embeded_C_CompilationProcess.pdf
0100_Embeded_C_CompilationProcess.pdf
 
Part II: LLVM Intermediate Representation
Part II: LLVM Intermediate RepresentationPart II: LLVM Intermediate Representation
Part II: LLVM Intermediate Representation
 
Appsec obfuscator reloaded
Appsec obfuscator reloadedAppsec obfuscator reloaded
Appsec obfuscator reloaded
 
Mario
MarioMario
Mario
 
Pragmatic Optimization in Modern Programming - Demystifying the Compiler
Pragmatic Optimization in Modern Programming - Demystifying the CompilerPragmatic Optimization in Modern Programming - Demystifying the Compiler
Pragmatic Optimization in Modern Programming - Demystifying the Compiler
 
Using Smalltalk for controlling robotics systems
Using Smalltalk for controlling robotics systemsUsing Smalltalk for controlling robotics systems
Using Smalltalk for controlling robotics systems
 
C Under Linux
C Under LinuxC Under Linux
C Under Linux
 
Fast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible JavaFast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible Java
 
Create C++ Applications with the Persistent Memory Development Kit
Create C++ Applications with the Persistent Memory Development KitCreate C++ Applications with the Persistent Memory Development Kit
Create C++ Applications with the Persistent Memory Development Kit
 
掀起 Swift 的面紗
掀起 Swift 的面紗掀起 Swift 的面紗
掀起 Swift 的面紗
 
Demystify eBPF JIT Compiler
Demystify eBPF JIT CompilerDemystify eBPF JIT Compiler
Demystify eBPF JIT Compiler
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Último (20)

Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 

Statically Compiling Ruby with LLVM