SlideShare a Scribd company logo
1 of 32
Translating Classic
Arcade Games
to JavaScript
Norbert Kehrer
vienna.js Meetup, June 24, 2015
Automatic Program Translation
Is Exciting
 Objective: exact conversion of the original
 The traditional way: emulators
 Interesting alternative: static binary
translation (static recompilation)
 Examples: Asteroids (1979), Astro Fighter
(1980), Centipede (1981)
Translating 6502 to JavaScript
 Emulation vs. Recompilation of
„Asteroids“
 The Source: the 6502
 The Target: JavaScript
 „Naive“ Translation Patterns
 Code Optimization and the Exciting
Journey into Compiler Theory
The Asteroids Arcade Machine
is Based on the 6502 Processor
Program ROM
6800–7fff
Work RAM
0000–02ff
Vector ROM
5000–57ff
Vector RAM
4000–47ff
6502 DVG
Game Logic Video Hardware
Traditional Emulation of the
Hardware ...
Program ROM
6800–7fff
Work RAM
0000–02ff
Vector ROM
5000–57ff
Vector RAM
4000–47ff
6502 DVG
Emulator in
JavaScript
... or Translating the Game
Program to JavaScript, …
Program ROM
6800–7fff
Work RAM
0000–02ff
Vector ROM
5000–57ff
Vector RAM
4000–47ff
6502 DVG
JavaScript
Emulator in
JavaScript
… and by that Create a Stand-
Alone Application
Program ROM
6800–7fff
Work RAM
0000–02ff
Vector ROM
5000–57ff
Vector RAM
4000–47ff
6502 DVG
JavaScript
Emulator in
JavaScript
Translating 6502 to JavaScript
 Emulation vs. Recompilation of
„Asteroids“
 The Source: the 6502
 The Target: JavaScript
 „Naive“ Translation Patterns
 Code Optimization and the Exciting
Journey into Compiler Theory
The 6502 was a Popular
Microprocessor in the 1980s
The 6502 Is Simple and Has
Only a Few Registers
Accumulator (A)
X Register (X)
Y Register (Y)
Program Counter (PC)
Flags: NV-BDIZC
00000001 Stack Pointer (S)
0000-00ff: Zero Page
0100-01ff: Stack
0200-ffff: Program
Registers Memory
The 6502 Instructions Can Have
Three Formats
Op Code
Op Code
Para-
meter
Op Code
Address
Low
Address
High
$a9 $03 … lda #3
$8d $07 $19 … sta $1907
$0a … asl
Some Instruction Examples
 lda #1 Load accu with 1
 sta 1000 Store accu in 1000
 inx Add 1 to X
 adc #7 Add 7 to the accu
 jmp 3000 Jump to 3000
 beq 2000 Conditional branch,
if Z (zero) flag is set
Translating 6502 to JavaScript
 Emulation vs. Recompilation of
„Asteroids“
 The Source: the 6502
 The Target: JavaScript
 „Naive“ Translation Patterns
 Code Optimization and the Exciting
Journey into Compiler Theory
JavaScript is the Target
 Variables and arrays
 Assignments and arithmetics
 if (cond) { stmt1 } else { stmt2 };
 switch (var) {
case a: stmt1; break;
case b: stmt2; break;
case c: stmt3; break;
…
};
Translating 6502 to JavaScript
 Emulation vs. Recompilation of
„Asteroids“
 The Source: the 6502
 The Target: JavaScript
 „Naive“ Translation Patterns
 Code Optimization and the Exciting
Journey into Compiler Theory
First, Write a Disassembler …
…
6834: A2 44 ldx #$44
6836: A9 02 lda #$02
6838: 85 02 sta $02
683A: 86 03 stx $03
…
…
A2 44
A9 02
85 02
86 03
…
Program ROM
(from Asteroids)
Disassembler listing
Then, Make a Code Generator
Out of It
…
… ldx #$44 x=44;
… lda #$02 a=2;
… sta $02 mem[2]=a;
… stx $03 mem[3]=x;
…
…
A2 44
A9 02
85 02
86 03
…
Program ROM
(from Asteroids)
JavaScript code instead of disassembler listing
6502 Registers and Memory
Become Variables and Arrays
Accumulator
X register
Y register
C flag
N flag
…
Memory
var a;
var x;
var y;
var c;
var n;
var mem = new
Array(65536);
„Normal“ Instructions Are Easy
to Translate
lda 1000
sta 1001
inc 1000
ldx #10
sta 2000,x
inx
a = mem[1000];
mem[1001] = a;
mem[1000] =
(mem[1000]+1)&0xff;
x = 10;
mem[2000+x] = a;
x = (x+1) & 0xff;
„GOTO Considered Harmful“
Considered Harmful
…
1000: ldx #0 ; x = 0
1002: inx ; x = x + 1
1003: stx $d020 ; x  screen color
1006: jmp 1002 ; go to 1002
…
But, JavaScript has no (real) GOTO !
An Old „Fortran to C“ Trick
pc = 1000;
while (true) {
switch (pc) {
case 1000: x = 0; //ldx
case 1002: x = (x+1) & 0xff; //inx
case 1003: mem[0xd020] = x; //stx
case 1006: pc = 1002; break; //jmp
…
};
};
Case Labels Are Only Needed
For Jump Targets
pc = 1000;
while (true) {
switch (pc) {
case 1000: x = 0; //ldx
case 1002: x = (x+1) & 0xff; //inx
case 1003: mem[0xd020] = x; //stx
case 1006: pc = 1002; break; //jmp
…
};
};
Conditional Branches Become
“If” Statements
…
if (z === 1) { // beq 3000
pc = 3000;
break;
};
…
case 3000:
…
Dr. Sheldon Cooper‘s „Fun with
Flags“
 Many 6502 instructions set flags as their
side effect
 Example:
lda 1000 if zero  Z=1 else Z=0
if neg.  N=1 else N=0
beq 4711
…
Instructions Need Additional
Flag Calculation Code
lda 1000
lda 1000
a = mem[1000];
a = mem[1000];
if (a==0) z=1; else z=0;
if (a<0) n=1; else n=0;
 Resulting programs are correct but big
Translating 6502 to JavaScript
 Emulation vs. Recompilation of
„Asteroids“
 The Source: the 6502
 The Target: JavaScript
 „Naive“ Translation Patterns
 Code Optimization and the Exciting
Journey into Compiler Theory
Flag Calculations Are Often
Redundant …
lda 1000 a = mem[1000];
if (a==0) z=1; else z=0;
if (a<0) n=1; else n=0;
ldx 1200 x = mem[1200];
if (x==0) z=1; else z=0;
if (x<0) n=1; else n=0;
beq 4711 if (z==1) …
Flag Calculations Are Often
Redundant …
lda 1000 a = mem[1000];
if (a==0) z=1; else z=0;
if (a<0) n=1; else n=0;
ldx 1200 x = mem[1200];
if (x==0) z=1; else z=0;
if (x<0) n=1; else n=0;
beq 4711 if (z==1) …
?:
yes:
… But Not Always
lda 1000 a = mem[1000];
if (a==0) z=1; else z=0;
if (a<0) n=1; else n=0;
ldx 1200 x = mem[1200];
if (x==0) z=1; else z=0;
if (x<0) n=1; else n=0;
beq 4711 if (z==1) …
Redundant Code Elimination Is
Difficult and Interesting
 „Liveness analysis“ problem
 Solution with fixpoint iteration, or more
elegantly with Datalog programs
 Many exciting further directions:
More optimizations (combinations, high-level
structure detection,…)
LLVM
asm.js
Datalog, Logic Programming, …
Summary: From Asteroids to
Liveness Analysis
 Browser-playable „Asteroids“ as an
example
 6502 Processor
 Translating 6502 code to JavaScript
 Optimizing: Redundant Code Elimination
Thank you!
http://members.aon.at/nkehrer/

More Related Content

What's hot

Senior design project code for PPG
Senior design project code for PPGSenior design project code for PPG
Senior design project code for PPGFrankDin1
 
C++ AMP 실천 및 적용 전략
C++ AMP 실천 및 적용 전략 C++ AMP 실천 및 적용 전략
C++ AMP 실천 및 적용 전략 명신 김
 
A compact zero knowledge proof to restrict message space in homomorphic encry...
A compact zero knowledge proof to restrict message space in homomorphic encry...A compact zero knowledge proof to restrict message space in homomorphic encry...
A compact zero knowledge proof to restrict message space in homomorphic encry...MITSUNARI Shigeo
 
COMPUTER GRAPHICS LAB MANUAL
COMPUTER GRAPHICS LAB MANUALCOMPUTER GRAPHICS LAB MANUAL
COMPUTER GRAPHICS LAB MANUALVivek Kumar Sinha
 
How to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJITHow to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJITEgor Bogatov
 
What&rsquo;s new in Visual C++
What&rsquo;s new in Visual C++What&rsquo;s new in Visual C++
What&rsquo;s new in Visual C++Microsoft
 
RedisConf18 - Lower Latency Graph Queries in Cypher with Redis Graph
RedisConf18 - Lower Latency Graph Queries in Cypher with Redis GraphRedisConf18 - Lower Latency Graph Queries in Cypher with Redis Graph
RedisConf18 - Lower Latency Graph Queries in Cypher with Redis GraphRedis Labs
 
Introduction to Stockfish bitboard representation and magic bitboard
Introduction to Stockfish bitboard representation and magic bitboardIntroduction to Stockfish bitboard representation and magic bitboard
Introduction to Stockfish bitboard representation and magic bitboardTaiyou Kuo
 
Anomalies in X-Ray Engine
Anomalies in X-Ray EngineAnomalies in X-Ray Engine
Anomalies in X-Ray EnginePVS-Studio
 
Functional Design Explained (David Sankel CppCon 2015)
Functional Design Explained (David Sankel CppCon 2015)Functional Design Explained (David Sankel CppCon 2015)
Functional Design Explained (David Sankel CppCon 2015)sankeld
 
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizationsEgor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizationsEgor Bogatov
 
PVS-Studio for Linux Went on a Tour Around Disney
PVS-Studio for Linux Went on a Tour Around DisneyPVS-Studio for Linux Went on a Tour Around Disney
PVS-Studio for Linux Went on a Tour Around DisneyPVS-Studio
 
Lifted-ElGamal暗号を用いた任意関数演算の二者間秘密計算プロトコルのmaliciousモデルにおける効率化
Lifted-ElGamal暗号を用いた任意関数演算の二者間秘密計算プロトコルのmaliciousモデルにおける効率化Lifted-ElGamal暗号を用いた任意関数演算の二者間秘密計算プロトコルのmaliciousモデルにおける効率化
Lifted-ElGamal暗号を用いた任意関数演算の二者間秘密計算プロトコルのmaliciousモデルにおける効率化MITSUNARI Shigeo
 
Computer Graphics Lab
Computer Graphics LabComputer Graphics Lab
Computer Graphics LabNeil Mathew
 
Graphics practical lab manual
Graphics practical lab manualGraphics practical lab manual
Graphics practical lab manualVivek Kumar Sinha
 
On using Haskell DSL - CLaSH, to implement a simple digital stopwatch on FPGA
On using Haskell DSL - CLaSH, to implement a simple digital stopwatch on FPGAOn using Haskell DSL - CLaSH, to implement a simple digital stopwatch on FPGA
On using Haskell DSL - CLaSH, to implement a simple digital stopwatch on FPGAmjgajda
 
Roberto Gallea: Workshop Arduino, giorno #2 Arduino + Processing
Roberto Gallea: Workshop Arduino, giorno #2 Arduino + ProcessingRoberto Gallea: Workshop Arduino, giorno #2 Arduino + Processing
Roberto Gallea: Workshop Arduino, giorno #2 Arduino + ProcessingDemetrio Siragusa
 
Tiramisu をちょっと、味見してみました。
Tiramisu をちょっと、味見してみました。Tiramisu をちょっと、味見してみました。
Tiramisu をちょっと、味見してみました。Mr. Vengineer
 

What's hot (20)

Senior design project code for PPG
Senior design project code for PPGSenior design project code for PPG
Senior design project code for PPG
 
C++ AMP 실천 및 적용 전략
C++ AMP 실천 및 적용 전략 C++ AMP 실천 및 적용 전략
C++ AMP 실천 및 적용 전략
 
OpenGL L06-Performance
OpenGL L06-PerformanceOpenGL L06-Performance
OpenGL L06-Performance
 
A compact zero knowledge proof to restrict message space in homomorphic encry...
A compact zero knowledge proof to restrict message space in homomorphic encry...A compact zero knowledge proof to restrict message space in homomorphic encry...
A compact zero knowledge proof to restrict message space in homomorphic encry...
 
COMPUTER GRAPHICS LAB MANUAL
COMPUTER GRAPHICS LAB MANUALCOMPUTER GRAPHICS LAB MANUAL
COMPUTER GRAPHICS LAB MANUAL
 
How to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJITHow to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJIT
 
What&rsquo;s new in Visual C++
What&rsquo;s new in Visual C++What&rsquo;s new in Visual C++
What&rsquo;s new in Visual C++
 
RedisConf18 - Lower Latency Graph Queries in Cypher with Redis Graph
RedisConf18 - Lower Latency Graph Queries in Cypher with Redis GraphRedisConf18 - Lower Latency Graph Queries in Cypher with Redis Graph
RedisConf18 - Lower Latency Graph Queries in Cypher with Redis Graph
 
Introduction to Stockfish bitboard representation and magic bitboard
Introduction to Stockfish bitboard representation and magic bitboardIntroduction to Stockfish bitboard representation and magic bitboard
Introduction to Stockfish bitboard representation and magic bitboard
 
Anomalies in X-Ray Engine
Anomalies in X-Ray EngineAnomalies in X-Ray Engine
Anomalies in X-Ray Engine
 
Functional Design Explained (David Sankel CppCon 2015)
Functional Design Explained (David Sankel CppCon 2015)Functional Design Explained (David Sankel CppCon 2015)
Functional Design Explained (David Sankel CppCon 2015)
 
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizationsEgor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
 
PVS-Studio for Linux Went on a Tour Around Disney
PVS-Studio for Linux Went on a Tour Around DisneyPVS-Studio for Linux Went on a Tour Around Disney
PVS-Studio for Linux Went on a Tour Around Disney
 
Lifted-ElGamal暗号を用いた任意関数演算の二者間秘密計算プロトコルのmaliciousモデルにおける効率化
Lifted-ElGamal暗号を用いた任意関数演算の二者間秘密計算プロトコルのmaliciousモデルにおける効率化Lifted-ElGamal暗号を用いた任意関数演算の二者間秘密計算プロトコルのmaliciousモデルにおける効率化
Lifted-ElGamal暗号を用いた任意関数演算の二者間秘密計算プロトコルのmaliciousモデルにおける効率化
 
Computer Graphics Lab
Computer Graphics LabComputer Graphics Lab
Computer Graphics Lab
 
Advance java
Advance javaAdvance java
Advance java
 
Graphics practical lab manual
Graphics practical lab manualGraphics practical lab manual
Graphics practical lab manual
 
On using Haskell DSL - CLaSH, to implement a simple digital stopwatch on FPGA
On using Haskell DSL - CLaSH, to implement a simple digital stopwatch on FPGAOn using Haskell DSL - CLaSH, to implement a simple digital stopwatch on FPGA
On using Haskell DSL - CLaSH, to implement a simple digital stopwatch on FPGA
 
Roberto Gallea: Workshop Arduino, giorno #2 Arduino + Processing
Roberto Gallea: Workshop Arduino, giorno #2 Arduino + ProcessingRoberto Gallea: Workshop Arduino, giorno #2 Arduino + Processing
Roberto Gallea: Workshop Arduino, giorno #2 Arduino + Processing
 
Tiramisu をちょっと、味見してみました。
Tiramisu をちょっと、味見してみました。Tiramisu をちょっと、味見してみました。
Tiramisu をちょっと、味見してみました。
 

Viewers also liked

Übersetzen alter Arcade-Spiele in JavaScript
Übersetzen alter Arcade-Spiele in JavaScriptÜbersetzen alter Arcade-Spiele in JavaScript
Übersetzen alter Arcade-Spiele in JavaScriptnorbert_kehrer
 
Ein Entwickler ist mehr als nur ein Applications-Coder | C.Habermueller
Ein Entwickler ist mehr als nur ein Applications-Coder | C.HabermuellerEin Entwickler ist mehr als nur ein Applications-Coder | C.Habermueller
Ein Entwickler ist mehr als nur ein Applications-Coder | C.HabermuellerChristian Habermueller
 
Produktives Arbeiten mit freier Software | C.Habermueller
Produktives Arbeiten mit freier Software | C.HabermuellerProduktives Arbeiten mit freier Software | C.Habermueller
Produktives Arbeiten mit freier Software | C.HabermuellerChristian Habermueller
 
Emulation von HP-Taschenrechnern auf dem Atari 800XL
Emulation von HP-Taschenrechnern auf dem Atari 800XLEmulation von HP-Taschenrechnern auf dem Atari 800XL
Emulation von HP-Taschenrechnern auf dem Atari 800XLnorbert_kehrer
 
Rapid Application Development | C.Habermueller
Rapid Application Development | C.HabermuellerRapid Application Development | C.Habermueller
Rapid Application Development | C.HabermuellerChristian Habermueller
 
Service Operation mit ITIL | C.Habermueller
Service Operation mit ITIL | C.HabermuellerService Operation mit ITIL | C.Habermueller
Service Operation mit ITIL | C.HabermuellerChristian Habermueller
 
Java & Notes - Mit Eclipse neue Features für Notes entwickeln | C.Habermueller
Java & Notes - Mit Eclipse neue Features für Notes entwickeln | C.HabermuellerJava & Notes - Mit Eclipse neue Features für Notes entwickeln | C.Habermueller
Java & Notes - Mit Eclipse neue Features für Notes entwickeln | C.HabermuellerChristian Habermueller
 
Domino Security mit ITIL | C.Habermueller
Domino Security mit ITIL | C.HabermuellerDomino Security mit ITIL | C.Habermueller
Domino Security mit ITIL | C.HabermuellerChristian Habermueller
 

Viewers also liked (10)

Übersetzen alter Arcade-Spiele in JavaScript
Übersetzen alter Arcade-Spiele in JavaScriptÜbersetzen alter Arcade-Spiele in JavaScript
Übersetzen alter Arcade-Spiele in JavaScript
 
Ein Entwickler ist mehr als nur ein Applications-Coder | C.Habermueller
Ein Entwickler ist mehr als nur ein Applications-Coder | C.HabermuellerEin Entwickler ist mehr als nur ein Applications-Coder | C.Habermueller
Ein Entwickler ist mehr als nur ein Applications-Coder | C.Habermueller
 
Visita a Línea Directa Aseguradora, nueva actividad esden FIELD TRIPS en el M...
Visita a Línea Directa Aseguradora, nueva actividad esden FIELD TRIPS en el M...Visita a Línea Directa Aseguradora, nueva actividad esden FIELD TRIPS en el M...
Visita a Línea Directa Aseguradora, nueva actividad esden FIELD TRIPS en el M...
 
Produktives Arbeiten mit freier Software | C.Habermueller
Produktives Arbeiten mit freier Software | C.HabermuellerProduktives Arbeiten mit freier Software | C.Habermueller
Produktives Arbeiten mit freier Software | C.Habermueller
 
Emulation von HP-Taschenrechnern auf dem Atari 800XL
Emulation von HP-Taschenrechnern auf dem Atari 800XLEmulation von HP-Taschenrechnern auf dem Atari 800XL
Emulation von HP-Taschenrechnern auf dem Atari 800XL
 
Rapid Application Development | C.Habermueller
Rapid Application Development | C.HabermuellerRapid Application Development | C.Habermueller
Rapid Application Development | C.Habermueller
 
Service Operation mit ITIL | C.Habermueller
Service Operation mit ITIL | C.HabermuellerService Operation mit ITIL | C.Habermueller
Service Operation mit ITIL | C.Habermueller
 
Java & Notes - Mit Eclipse neue Features für Notes entwickeln | C.Habermueller
Java & Notes - Mit Eclipse neue Features für Notes entwickeln | C.HabermuellerJava & Notes - Mit Eclipse neue Features für Notes entwickeln | C.Habermueller
Java & Notes - Mit Eclipse neue Features für Notes entwickeln | C.Habermueller
 
Impressionen VCFE 11.0
Impressionen VCFE 11.0Impressionen VCFE 11.0
Impressionen VCFE 11.0
 
Domino Security mit ITIL | C.Habermueller
Domino Security mit ITIL | C.HabermuellerDomino Security mit ITIL | C.Habermueller
Domino Security mit ITIL | C.Habermueller
 

Similar to Translating Classic Arcade Games like Asteroids to JavaScript and Optimizing the Code

Best Bugs from Games: Fellow Programmers' Mistakes
Best Bugs from Games: Fellow Programmers' MistakesBest Bugs from Games: Fellow Programmers' Mistakes
Best Bugs from Games: Fellow Programmers' MistakesAndrey Karpov
 
The Joy of ServerSide Swift Development
The Joy  of ServerSide Swift DevelopmentThe Joy  of ServerSide Swift Development
The Joy of ServerSide Swift DevelopmentGiordano Scalzo
 
The Joy Of Server Side Swift Development
The Joy Of Server Side Swift DevelopmentThe Joy Of Server Side Swift Development
The Joy Of Server Side Swift DevelopmentGiordano Scalzo
 
The Joy of Server Side Swift Development
The Joy  of Server Side Swift DevelopmentThe Joy  of Server Side Swift Development
The Joy of Server Side Swift DevelopmentGiordano Scalzo
 
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...DevGAMM Conference
 
Android RenderScript on LLVM
Android RenderScript on LLVMAndroid RenderScript on LLVM
Android RenderScript on LLVMJohn Lee
 
The Unicorn Getting Interested in KDE
The Unicorn Getting Interested in KDEThe Unicorn Getting Interested in KDE
The Unicorn Getting Interested in KDEAndrey Karpov
 
Legacy projects: how to win the race
Legacy projects: how to win the raceLegacy projects: how to win the race
Legacy projects: how to win the raceVictor_Cr
 
Minko stage3d workshop_20130525
Minko stage3d workshop_20130525Minko stage3d workshop_20130525
Minko stage3d workshop_20130525Minko3D
 
The Unicorn's Travel to the Microcosm
The Unicorn's Travel to the MicrocosmThe Unicorn's Travel to the Microcosm
The Unicorn's Travel to the MicrocosmAndrey Karpov
 
SFO15-500: VIXL
SFO15-500: VIXLSFO15-500: VIXL
SFO15-500: VIXLLinaro
 
ADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersBartosz Kosarzycki
 
OWASP Poland Day 2018 - Pedro Fortuna - Are your Java Script based protection...
OWASP Poland Day 2018 - Pedro Fortuna - Are your Java Script based protection...OWASP Poland Day 2018 - Pedro Fortuna - Are your Java Script based protection...
OWASP Poland Day 2018 - Pedro Fortuna - Are your Java Script based protection...OWASP
 
zkStudyClub: CirC and Compiling Programs to Circuits
zkStudyClub: CirC and Compiling Programs to CircuitszkStudyClub: CirC and Compiling Programs to Circuits
zkStudyClub: CirC and Compiling Programs to CircuitsAlex Pruden
 
Beyond the Query – Bringing Complex Access Patterns to NoSQL with DataStax - ...
Beyond the Query – Bringing Complex Access Patterns to NoSQL with DataStax - ...Beyond the Query – Bringing Complex Access Patterns to NoSQL with DataStax - ...
Beyond the Query – Bringing Complex Access Patterns to NoSQL with DataStax - ...StampedeCon
 
Vc4c development of opencl compiler for videocore4
Vc4c  development of opencl compiler for videocore4Vc4c  development of opencl compiler for videocore4
Vc4c development of opencl compiler for videocore4nomaddo
 
Kotlin: forse è la volta buona (Trento)
Kotlin: forse è la volta buona (Trento)Kotlin: forse è la volta buona (Trento)
Kotlin: forse è la volta buona (Trento)Davide Cerbo
 
A verifiable random function with short proofs and keys
A verifiable random function with short proofs and keysA verifiable random function with short proofs and keys
A verifiable random function with short proofs and keysAleksandr Yampolskiy
 
Java Keeps Throttling Up!
Java Keeps Throttling Up!Java Keeps Throttling Up!
Java Keeps Throttling Up!José Paumard
 

Similar to Translating Classic Arcade Games like Asteroids to JavaScript and Optimizing the Code (20)

Best Bugs from Games: Fellow Programmers' Mistakes
Best Bugs from Games: Fellow Programmers' MistakesBest Bugs from Games: Fellow Programmers' Mistakes
Best Bugs from Games: Fellow Programmers' Mistakes
 
The Joy of ServerSide Swift Development
The Joy  of ServerSide Swift DevelopmentThe Joy  of ServerSide Swift Development
The Joy of ServerSide Swift Development
 
The Joy Of Server Side Swift Development
The Joy Of Server Side Swift DevelopmentThe Joy Of Server Side Swift Development
The Joy Of Server Side Swift Development
 
The Joy of Server Side Swift Development
The Joy  of Server Side Swift DevelopmentThe Joy  of Server Side Swift Development
The Joy of Server Side Swift Development
 
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
 
Android RenderScript on LLVM
Android RenderScript on LLVMAndroid RenderScript on LLVM
Android RenderScript on LLVM
 
The Unicorn Getting Interested in KDE
The Unicorn Getting Interested in KDEThe Unicorn Getting Interested in KDE
The Unicorn Getting Interested in KDE
 
Legacy projects: how to win the race
Legacy projects: how to win the raceLegacy projects: how to win the race
Legacy projects: how to win the race
 
Minko stage3d workshop_20130525
Minko stage3d workshop_20130525Minko stage3d workshop_20130525
Minko stage3d workshop_20130525
 
The Unicorn's Travel to the Microcosm
The Unicorn's Travel to the MicrocosmThe Unicorn's Travel to the Microcosm
The Unicorn's Travel to the Microcosm
 
SFO15-500: VIXL
SFO15-500: VIXLSFO15-500: VIXL
SFO15-500: VIXL
 
ADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developers
 
OWASP Poland Day 2018 - Pedro Fortuna - Are your Java Script based protection...
OWASP Poland Day 2018 - Pedro Fortuna - Are your Java Script based protection...OWASP Poland Day 2018 - Pedro Fortuna - Are your Java Script based protection...
OWASP Poland Day 2018 - Pedro Fortuna - Are your Java Script based protection...
 
zkStudyClub: CirC and Compiling Programs to Circuits
zkStudyClub: CirC and Compiling Programs to CircuitszkStudyClub: CirC and Compiling Programs to Circuits
zkStudyClub: CirC and Compiling Programs to Circuits
 
Beyond the Query – Bringing Complex Access Patterns to NoSQL with DataStax - ...
Beyond the Query – Bringing Complex Access Patterns to NoSQL with DataStax - ...Beyond the Query – Bringing Complex Access Patterns to NoSQL with DataStax - ...
Beyond the Query – Bringing Complex Access Patterns to NoSQL with DataStax - ...
 
Vc4c development of opencl compiler for videocore4
Vc4c  development of opencl compiler for videocore4Vc4c  development of opencl compiler for videocore4
Vc4c development of opencl compiler for videocore4
 
Kotlin: forse è la volta buona (Trento)
Kotlin: forse è la volta buona (Trento)Kotlin: forse è la volta buona (Trento)
Kotlin: forse è la volta buona (Trento)
 
Rsltollvm
RsltollvmRsltollvm
Rsltollvm
 
A verifiable random function with short proofs and keys
A verifiable random function with short proofs and keysA verifiable random function with short proofs and keys
A verifiable random function with short proofs and keys
 
Java Keeps Throttling Up!
Java Keeps Throttling Up!Java Keeps Throttling Up!
Java Keeps Throttling Up!
 

Recently uploaded

Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 

Recently uploaded (20)

Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 

Translating Classic Arcade Games like Asteroids to JavaScript and Optimizing the Code

  • 1. Translating Classic Arcade Games to JavaScript Norbert Kehrer vienna.js Meetup, June 24, 2015
  • 2. Automatic Program Translation Is Exciting  Objective: exact conversion of the original  The traditional way: emulators  Interesting alternative: static binary translation (static recompilation)  Examples: Asteroids (1979), Astro Fighter (1980), Centipede (1981)
  • 3. Translating 6502 to JavaScript  Emulation vs. Recompilation of „Asteroids“  The Source: the 6502  The Target: JavaScript  „Naive“ Translation Patterns  Code Optimization and the Exciting Journey into Compiler Theory
  • 4. The Asteroids Arcade Machine is Based on the 6502 Processor Program ROM 6800–7fff Work RAM 0000–02ff Vector ROM 5000–57ff Vector RAM 4000–47ff 6502 DVG Game Logic Video Hardware
  • 5. Traditional Emulation of the Hardware ... Program ROM 6800–7fff Work RAM 0000–02ff Vector ROM 5000–57ff Vector RAM 4000–47ff 6502 DVG Emulator in JavaScript
  • 6. ... or Translating the Game Program to JavaScript, … Program ROM 6800–7fff Work RAM 0000–02ff Vector ROM 5000–57ff Vector RAM 4000–47ff 6502 DVG JavaScript Emulator in JavaScript
  • 7. … and by that Create a Stand- Alone Application Program ROM 6800–7fff Work RAM 0000–02ff Vector ROM 5000–57ff Vector RAM 4000–47ff 6502 DVG JavaScript Emulator in JavaScript
  • 8. Translating 6502 to JavaScript  Emulation vs. Recompilation of „Asteroids“  The Source: the 6502  The Target: JavaScript  „Naive“ Translation Patterns  Code Optimization and the Exciting Journey into Compiler Theory
  • 9. The 6502 was a Popular Microprocessor in the 1980s
  • 10. The 6502 Is Simple and Has Only a Few Registers Accumulator (A) X Register (X) Y Register (Y) Program Counter (PC) Flags: NV-BDIZC 00000001 Stack Pointer (S) 0000-00ff: Zero Page 0100-01ff: Stack 0200-ffff: Program Registers Memory
  • 11. The 6502 Instructions Can Have Three Formats Op Code Op Code Para- meter Op Code Address Low Address High $a9 $03 … lda #3 $8d $07 $19 … sta $1907 $0a … asl
  • 12. Some Instruction Examples  lda #1 Load accu with 1  sta 1000 Store accu in 1000  inx Add 1 to X  adc #7 Add 7 to the accu  jmp 3000 Jump to 3000  beq 2000 Conditional branch, if Z (zero) flag is set
  • 13. Translating 6502 to JavaScript  Emulation vs. Recompilation of „Asteroids“  The Source: the 6502  The Target: JavaScript  „Naive“ Translation Patterns  Code Optimization and the Exciting Journey into Compiler Theory
  • 14. JavaScript is the Target  Variables and arrays  Assignments and arithmetics  if (cond) { stmt1 } else { stmt2 };  switch (var) { case a: stmt1; break; case b: stmt2; break; case c: stmt3; break; … };
  • 15. Translating 6502 to JavaScript  Emulation vs. Recompilation of „Asteroids“  The Source: the 6502  The Target: JavaScript  „Naive“ Translation Patterns  Code Optimization and the Exciting Journey into Compiler Theory
  • 16. First, Write a Disassembler … … 6834: A2 44 ldx #$44 6836: A9 02 lda #$02 6838: 85 02 sta $02 683A: 86 03 stx $03 … … A2 44 A9 02 85 02 86 03 … Program ROM (from Asteroids) Disassembler listing
  • 17. Then, Make a Code Generator Out of It … … ldx #$44 x=44; … lda #$02 a=2; … sta $02 mem[2]=a; … stx $03 mem[3]=x; … … A2 44 A9 02 85 02 86 03 … Program ROM (from Asteroids) JavaScript code instead of disassembler listing
  • 18. 6502 Registers and Memory Become Variables and Arrays Accumulator X register Y register C flag N flag … Memory var a; var x; var y; var c; var n; var mem = new Array(65536);
  • 19. „Normal“ Instructions Are Easy to Translate lda 1000 sta 1001 inc 1000 ldx #10 sta 2000,x inx a = mem[1000]; mem[1001] = a; mem[1000] = (mem[1000]+1)&0xff; x = 10; mem[2000+x] = a; x = (x+1) & 0xff;
  • 20. „GOTO Considered Harmful“ Considered Harmful … 1000: ldx #0 ; x = 0 1002: inx ; x = x + 1 1003: stx $d020 ; x  screen color 1006: jmp 1002 ; go to 1002 … But, JavaScript has no (real) GOTO !
  • 21. An Old „Fortran to C“ Trick pc = 1000; while (true) { switch (pc) { case 1000: x = 0; //ldx case 1002: x = (x+1) & 0xff; //inx case 1003: mem[0xd020] = x; //stx case 1006: pc = 1002; break; //jmp … }; };
  • 22. Case Labels Are Only Needed For Jump Targets pc = 1000; while (true) { switch (pc) { case 1000: x = 0; //ldx case 1002: x = (x+1) & 0xff; //inx case 1003: mem[0xd020] = x; //stx case 1006: pc = 1002; break; //jmp … }; };
  • 23. Conditional Branches Become “If” Statements … if (z === 1) { // beq 3000 pc = 3000; break; }; … case 3000: …
  • 24. Dr. Sheldon Cooper‘s „Fun with Flags“  Many 6502 instructions set flags as their side effect  Example: lda 1000 if zero  Z=1 else Z=0 if neg.  N=1 else N=0 beq 4711 …
  • 25. Instructions Need Additional Flag Calculation Code lda 1000 lda 1000 a = mem[1000]; a = mem[1000]; if (a==0) z=1; else z=0; if (a<0) n=1; else n=0;  Resulting programs are correct but big
  • 26. Translating 6502 to JavaScript  Emulation vs. Recompilation of „Asteroids“  The Source: the 6502  The Target: JavaScript  „Naive“ Translation Patterns  Code Optimization and the Exciting Journey into Compiler Theory
  • 27. Flag Calculations Are Often Redundant … lda 1000 a = mem[1000]; if (a==0) z=1; else z=0; if (a<0) n=1; else n=0; ldx 1200 x = mem[1200]; if (x==0) z=1; else z=0; if (x<0) n=1; else n=0; beq 4711 if (z==1) …
  • 28. Flag Calculations Are Often Redundant … lda 1000 a = mem[1000]; if (a==0) z=1; else z=0; if (a<0) n=1; else n=0; ldx 1200 x = mem[1200]; if (x==0) z=1; else z=0; if (x<0) n=1; else n=0; beq 4711 if (z==1) …
  • 29. ?: yes: … But Not Always lda 1000 a = mem[1000]; if (a==0) z=1; else z=0; if (a<0) n=1; else n=0; ldx 1200 x = mem[1200]; if (x==0) z=1; else z=0; if (x<0) n=1; else n=0; beq 4711 if (z==1) …
  • 30. Redundant Code Elimination Is Difficult and Interesting  „Liveness analysis“ problem  Solution with fixpoint iteration, or more elegantly with Datalog programs  Many exciting further directions: More optimizations (combinations, high-level structure detection,…) LLVM asm.js Datalog, Logic Programming, …
  • 31. Summary: From Asteroids to Liveness Analysis  Browser-playable „Asteroids“ as an example  6502 Processor  Translating 6502 code to JavaScript  Optimizing: Redundant Code Elimination