SlideShare a Scribd company logo
S.Ducasse 1
QuickTime™ and aTIFF (Uncompressed) decompressorare needed to see this picture.
Marcus Denker
denker@iam.unibe.ch
Working with
Bytecodes: IRBuilder and
InstructionStream
S.Ducasse 2
License: CC-Attribution-ShareAlike 2.0
http://creativecommons.org/licenses/by-sa/2.0/
S.Ducasse 3
Reasons for working with Bytecode
• Generating Bytecode
• Implementing compilers for other languages
• Experimentation with new language features
• Parsing and Interpretation:
• Analysis
• Decompilation (for systems without source)
• Pretty printing
• Interpretation: Debugger, Profiler
S.Ducasse 4
Overview
• Squeak Bytecodes
• Examples: Generating Bytecode
• with IRBuilder
• Decoding Bytecodes
• Bytecode Execution
S.Ducasse 5
The SqueakVirtual Machine
• Virtual machine provides a virtual processor
• Bytecode:The ‘machinecode’ of the virtual machine
• Smalltalk (like Java): Stack machine
• easy to implement interpreters for different processors
• most hardware processors are register machines
• SqueakVM: Implemented in Slang
• Slang: Subset of Smalltalk. (”C with Smalltalk Syntax”)
• Translated to C
S.Ducasse 6
Bytecode in the CompiledMethod
• CompiledMethods format:
Header
Literals
Bytecode
Trailer
Pointer to
Source
Array of all
Literal Objects
Number of
temps, literals...
(Number>>#asInteger)inspect
S.Ducasse 7
Bytecodes: Single or multibyte
• Different forms of bytecodes:
• Single bytecodes:
• Example: 120: push self
• Groups of similar bytecodes
• 16: push temp 1
• 17: push temp 2
• up to 31
• Multibyte bytecodes
• Problem: 4bit offset may be too small
• Solution: Use the following byte as offset
• Example: Jumps need to encode large jump offsets
OffsetType
4bits 4bits
S.Ducasse 8
Example: Number>>asInteger
• Smalltalk code:
• Symbolic Bytecode
Number>>asInteger
"Answer an Integer nearest the receiver toward zero."
^self truncated
9 <70> self
10 <D0> send: truncated
11 <7C> returnTop
S.Ducasse 9
Example: Step by Step
• 9 <70> self
• The receiver (self) is pushed on the stack
• 10 <D0> send: truncated
• Bytecode 208: send litereral selector 1
• Get the selector from the first literal
• start message lookup in the class of the object
that is top of the stack
• result is pushed on the stack
• 11 <7C> returnTop
• return the object on top of the stack to the
calling method
S.Ducasse 10
Squeak Bytecodes
• 256 Bytecodes, four groups:
• Stack Bytecodes
• Stack manipulation: push / pop / dup
• Send Bytecodes
• Invoke Methods
• Return Bytecodes
• Return to caller
• Jump Bytecodes
• Control flow inside a method
S.Ducasse 11
Stack Bytecodes
• push and store, e.g. temps, instVars, literals
• e.g: 16 - 31: push instance variable
• Push Constants (False/True/Nil/1/0/2/-1)
• Push self, thisContext
• duplicate top of stack
• pop
S.Ducasse 12
Sends and Returns
• Sends: receiver is on top of stack
• Normal send
• Super Sends
• Hard-coded sends for efficiency, e.g. +, -
• Returns
• Return top of stack to the sender
• Return from a block
• Special bytecodes for return self, nil, true, false
(for efficiency)
S.Ducasse 13
Jump Bytecodes
• Control Flow inside one method
• Used to implement control-flow efficiently
• Example:
9 <76> pushConstant: 1
10 <77> pushConstant: 2
11 <B2> send: <
12 <99> jumpFalse: 15
13 <20> pushConstant: 'true'
14 <90> jumpTo: 16
15 <73> pushConstant: nil
16 <7C> returnTop
^ 1<2 ifTrue: ['true']
S.Ducasse 14
What you should have learned...
• ... dealing with bytecodes directly is possible, but very
boring.
• We want reusable abstractions that hide the details
(e.g. the different send bytecodes)
• We would like to have frameworks for
• Generating bytecode easily
• Parsing bytecode
• Evaluating bytecode
S.Ducasse 15
Generating Bytecodes
• IRBuilder
• Part of the new compiler (on SqueakMap)
• Like an Assembler for Squeak
S.Ducasse 16
IRBuilder: Simple Example
• Number>>asInteger
iRMethod := IRBuilder new
rargs: #(self); "receiver and args"
pushTemp: #self;
send: #truncated;
returnTop;
ir.
aCompiledMethod := iRMethod compiledMethod.
aCompiledMethod valueWithReceiver:3.5
arguments: #()
S.Ducasse 17
IRBuilder: Stack Manipulation
• popTop - remove the top of stack
• pushDup - push top of stack on the stack
• pushLiteral:
• pushReceiver - push self
• pushThisContext
S.Ducasse 18
IRBuilder: Symbolic Jumps
• Jump targets are resolved:
• Example: false ifTrue: [’true’] ifFalse: [’false’]
iRMethod := IRBuilder new
rargs: #(self); "receiver and args"
pushLiteral: false;
jumpAheadTo: #false if: false;
pushLiteral: 'true'; "ifTrue: ['true']"
jumpAheadTo: #end;
jumpAheadTarget: #false;
pushLiteral: 'false'; "ifFalse: ['false']"
jumpAheadTarget: #end;
returnTop;
ir.
S.Ducasse 19
IRBuiler: InstanceVariables
• Access by offset
• Read: getField:
• receiver on top of stack
• Write: setField:
• receiver and value on stack
• Example: set the first instance variable to 2
iRMethod := IRBuilder new
rargs: #(self); "receiver and args declarations"
pushLiteral: 2;
pushTemp: #self;
setField: 1;
pushTemp: #self;
returnTop;
ir.
aCompiledMethod := iRMethod compiledMethod.
aCompiledMethod valueWithReceiver: 1@2 arguments: #()
S.Ducasse 20
IRBuilder:TemporaryVariables
• Accessed by name
• Define with addTemp: / addTemps:
• Read with pushTemp:
• Write with storeTemp:
• Examle: set variables a and b, return value of a
iRMethod := IRBuilder new
rargs: #(self); "receiver and args"
addTemps: #(a b);
pushLiteral: 1;
storeTemp: #a;
pushLiteral: 2;
storeTemp: #b;
pushTemp: #a;
returnTop;
ir.
S.Ducasse 21
IRBuilder: Sends
• normal send
• super send
• The second parameter specifies the class were the
lookup starts.
....
builder send: #selector toSuperOf: aClass;
builder pushLiteral: ‘hello’
builder send: #size;
S.Ducasse 22
IRBuilder: Lessons learned
• IRBuilder: Easy bytecode generation
• Not part of Squeak yet
• Will be added to Squeak 3.9 or 4.0
• Next: Decoding bytecode
S.Ducasse 23
Parsing and Interpretation
• First step: Parse bytecode
• enough for easy analysis, pretty printing, decompilation
• Second step: Interpretation
• needed for simulation, complex analyis (e.g., profiling)
• Squeak provides frameworks for both:
• InstructionStream/InstructionClient (parsing)
• ContextPart (Interpretation)
S.Ducasse 24
The InstructionStream Hierarchy
InstructionStream
ContextPart
BlockContext
MethodContext
Decompiler
InstructionPrinter
InstVarRefLocator
BytecodeDecompiler
S.Ducasse 25
InstructionStream
• Parses the byte-encoded instructions
• State:
• pc: programm counter
• sender: the method (bad name!)
Object subclass: #InstructionStream
instanceVariableNames: 'sender pc'
classVariableNames: 'SpecialConstants'
poolDictionaries: ''
category: 'Kernel-Methods'
S.Ducasse 26
Usage
• Generate an instance:
• Now we can step through the bytecode with
• calls methods on a client object for the type of
bytecode, e.g.
• pushReceiver
• pushConstant: value
• pushReceiverVariable: offset
instrStream := IntructionStream on: aMethod
instrStream interpretNextInstructionFor: client
S.Ducasse 27
InstructionClient
• Abstract superclass
• Defines empty methods for all methods that
InstructionStream calls on a client
• For convienience:
• Client don’t need to inherit from this
Object subclass: #InstructionClient
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'Kernel-Methods'
S.Ducasse 28
Example:A test
InstructionClientTest>>testInstructions
"just interpret all of methods of Object"
| methods client scanner|
methods := Object methodDict values.
client := InstructionClient new.
methods do: [:method |
scanner := (InstructionStream on: method).
[scanner pc <= method endPC] whileTrue: [
self shouldnt: [scanner interpretNextInstructionFor: client] raise:
Error.
].
].
S.Ducasse 29
Example: Printing Bytecodes
• InstructionPrinter: Print the bytecodes as human
readable text
• Example: print the bytecode of Number>>asInteger:
String streamContents: [:str |
(InstructionPrinter on: Number>>#asInteger)
printInstructionsOn: str
]
result:
'9 <70> self
10 <D0> send: truncated
11 <7C> returnTop
'
S.Ducasse 30
InstructionPrinter
• Class Definition:
InstructionClient subclass: #InstructionPrinter
instanceVariableNames: 'method scanner
stream oldPC indent'
classVariableNames: ''
poolDictionaries: ''
category: 'Kernel-Methods'
S.Ducasse 31
InstructionPrinter
• Main Loop:
InstructionPrinter>>printInstructionsOn: aStream
"Append to the stream, aStream, a description of each
bytecode in the instruction stream."
| end |
stream := aStream.
scanner := InstructionStream on: method.
end := method endPC.
oldPC := scanner pc.
[scanner pc <= end]
whileTrue: [scanner interpretNextInstructionFor: self]
S.Ducasse 32
InstructionPrinter
• Overwrites methods form InstructionClient to print
the bytecodes as text
• e.g. the method for pushReceiver:
InstructionPrinter>>pushReceiver
"Print the Push Active Context's Receiver
on Top Of Stack bytecode."
self print: 'self'
S.Ducasse 33
Example: InstVarRefLocator
InstructionClient subclass: #InstVarRefLocator
instanceVariableNames: 'bingo'
....
interpretNextInstructionUsing: aScanner
bingo := false.
aScanner interpretNextInstructionFor: self.
^bingo
popIntoReceiverVariable: offset
bingo := true
pushReceiverVariable: offset
bingo := true
storeIntoReceiverVariable: offset
bingo := true
S.Ducasse 34
InstVarRefLocator
• CompiledMethod>>#hasInstVarRef
hasInstVarRef
"Answer whether the receiver references an instance variable."
| scanner end printer |
scanner := InstructionStream on: self.
printer := InstVarRefLocator new.
end := self endPC.
[scanner pc <= end] whileTrue: [
(printer interpretNextInstructionUsing: scanner) ifTrue: [^true].
].
^false
S.Ducasse 35
InstVarRefLocator
• Example for a simple bytecode analyzer
• Usage:
aMethod hasInstVarRef
(TestCase>>#debug) hasInstVarRef
true
(Integer>>#+) hasInstVarRef
false
S.Ducasse 36
Example: Decompiling to IR
• BytecodeDecompiler
• Usage:
InstructionStream subclass: #BytecodeDecompiler
instanceVariableNames: 'irBuilder blockFlag'
classVariableNames: ''
poolDictionaries: ''
category: 'Compiler-Bytecodes'
BytecodeDecompiler new decompile: (Number>>#asInteger)
S.Ducasse 37
Decompiling
• uses IRBuilder for building IR
• e.g. code for the bytecode pushReceiver:
BytecodeDecompiler>>pushReceiver
irBuilder pushReceiver
S.Ducasse 38
ContextPart: Execution Semantics
• Sometimes we need more than parsing
• “stepping” in the debugger
• system simulation for profiling
InstructionStream subclass: #ContextPart
instanceVariableNames: 'stackp'
classVariableNames: 'PrimitiveFailToken QuickStep'
poolDictionaries: ''
category: 'Kernel-Methods'
S.Ducasse 39
Simulation
• Provides a complete Bytecode interpreter
• Run a block with the simulator:
(ContextPart runSimulated: [3 factorial])
S.Ducasse 40
Profiling: MesageTally
• Usage:
• Other example:
MessageTally tallySends: [3 factorial]
This simulation took 0.0 seconds.
**Tree**
1 SmallInteger(Integer)>>factorial
1 SmallInteger(Integer)>>factorial
1 SmallInteger(Integer)>>factorial
1 SmallInteger(Integer)>>factorial
MessageTally tallySends: [’3’ + 1]
**Leaves**
4 SmallInteger(Integer)>>factorial
3 SmallInteger(Integer)>>factorial
1 BlockContext>>DoIt
S.Ducasse 41

More Related Content

What's hot

Runtime
RuntimeRuntime
Runtime
Jorge Ortiz
 
Dennis Benkert & Matthias Lübken - Patterns in a containerized world? - code....
Dennis Benkert & Matthias Lübken - Patterns in a containerized world? - code....Dennis Benkert & Matthias Lübken - Patterns in a containerized world? - code....
Dennis Benkert & Matthias Lübken - Patterns in a containerized world? - code....
AboutYouGmbH
 
8 - OOP - Syntax & Messages
8 - OOP - Syntax & Messages8 - OOP - Syntax & Messages
8 - OOP - Syntax & Messages
The World of Smalltalk
 
An Introduction to Twisted
An Introduction to TwistedAn Introduction to Twisted
An Introduction to Twisted
sdsern
 
What Makes Objective C Dynamic?
What Makes Objective C Dynamic?What Makes Objective C Dynamic?
What Makes Objective C Dynamic?
Kyle Oba
 
NodeJS: an Introduction
NodeJS: an IntroductionNodeJS: an Introduction
NodeJS: an Introduction
Roberto Casadei
 
06 - Qt Communication
06 - Qt Communication06 - Qt Communication
06 - Qt Communication
Andreas Jakl
 
Cp7 rpc
Cp7 rpcCp7 rpc
Ekon 25 Python4Delphi_MX475
Ekon 25 Python4Delphi_MX475Ekon 25 Python4Delphi_MX475
Ekon 25 Python4Delphi_MX475
Max Kleiner
 
Patterns for JVM languages JokerConf
Patterns for JVM languages JokerConfPatterns for JVM languages JokerConf
Patterns for JVM languages JokerConf
Jaroslaw Palka
 
Node.js System: The Approach
Node.js System: The ApproachNode.js System: The Approach
Node.js System: The Approach
Haci Murat Yaman
 
Pune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCDPune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCD
Prashant Rane
 
Other Approaches (Concurrency)
Other Approaches (Concurrency)Other Approaches (Concurrency)
Other Approaches (Concurrency)
Sri Prasanna
 
network programing lab file ,
network programing lab file ,network programing lab file ,
network programing lab file ,
AAlha PaiKra
 
Java Performance Tuning
Java Performance TuningJava Performance Tuning
Java Performance Tuning
Minh Hoang
 
Python twisted
Python twistedPython twisted
Python twisted
Mahendra M
 
Qt Framework Events Signals Threads
Qt Framework Events Signals ThreadsQt Framework Events Signals Threads
Qt Framework Events Signals Threads
Neera Mital
 
Objective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central DispatchObjective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central Dispatch
Matteo Battaglio
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrency
feng lee
 
C++ process new
C++ process newC++ process new
C++ process new
敬倫 林
 

What's hot (20)

Runtime
RuntimeRuntime
Runtime
 
Dennis Benkert & Matthias Lübken - Patterns in a containerized world? - code....
Dennis Benkert & Matthias Lübken - Patterns in a containerized world? - code....Dennis Benkert & Matthias Lübken - Patterns in a containerized world? - code....
Dennis Benkert & Matthias Lübken - Patterns in a containerized world? - code....
 
8 - OOP - Syntax & Messages
8 - OOP - Syntax & Messages8 - OOP - Syntax & Messages
8 - OOP - Syntax & Messages
 
An Introduction to Twisted
An Introduction to TwistedAn Introduction to Twisted
An Introduction to Twisted
 
What Makes Objective C Dynamic?
What Makes Objective C Dynamic?What Makes Objective C Dynamic?
What Makes Objective C Dynamic?
 
NodeJS: an Introduction
NodeJS: an IntroductionNodeJS: an Introduction
NodeJS: an Introduction
 
06 - Qt Communication
06 - Qt Communication06 - Qt Communication
06 - Qt Communication
 
Cp7 rpc
Cp7 rpcCp7 rpc
Cp7 rpc
 
Ekon 25 Python4Delphi_MX475
Ekon 25 Python4Delphi_MX475Ekon 25 Python4Delphi_MX475
Ekon 25 Python4Delphi_MX475
 
Patterns for JVM languages JokerConf
Patterns for JVM languages JokerConfPatterns for JVM languages JokerConf
Patterns for JVM languages JokerConf
 
Node.js System: The Approach
Node.js System: The ApproachNode.js System: The Approach
Node.js System: The Approach
 
Pune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCDPune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCD
 
Other Approaches (Concurrency)
Other Approaches (Concurrency)Other Approaches (Concurrency)
Other Approaches (Concurrency)
 
network programing lab file ,
network programing lab file ,network programing lab file ,
network programing lab file ,
 
Java Performance Tuning
Java Performance TuningJava Performance Tuning
Java Performance Tuning
 
Python twisted
Python twistedPython twisted
Python twisted
 
Qt Framework Events Signals Threads
Qt Framework Events Signals ThreadsQt Framework Events Signals Threads
Qt Framework Events Signals Threads
 
Objective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central DispatchObjective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central Dispatch
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrency
 
C++ process new
C++ process newC++ process new
C++ process new
 

Viewers also liked

Stoop 439-decorator
Stoop 439-decoratorStoop 439-decorator
Stoop 439-decorator
The World of Smalltalk
 
Stoop 436-strategy
Stoop 436-strategyStoop 436-strategy
Stoop 436-strategy
The World of Smalltalk
 
12 virtualmachine
12 virtualmachine12 virtualmachine
12 virtualmachine
The World of Smalltalk
 
Stoop 423-smalltalk idioms
Stoop 423-smalltalk idiomsStoop 423-smalltalk idioms
Stoop 423-smalltalk idioms
The World of Smalltalk
 
10 reflection
10 reflection10 reflection
10 reflection
The World of Smalltalk
 
05 seaside
05 seaside05 seaside
Stoop 413-abstract classes
Stoop 413-abstract classesStoop 413-abstract classes
Stoop 413-abstract classes
The World of Smalltalk
 
Stoop ed-class forreuse
Stoop ed-class forreuseStoop ed-class forreuse
Stoop ed-class forreuse
The World of Smalltalk
 
Stoop sed-class initialization
Stoop sed-class initializationStoop sed-class initialization
Stoop sed-class initialization
The World of Smalltalk
 
5 - OOP - Smalltalk in a Nutshell (c)
5 - OOP - Smalltalk in a Nutshell (c)5 - OOP - Smalltalk in a Nutshell (c)
5 - OOP - Smalltalk in a Nutshell (c)
The World of Smalltalk
 
14 - Exceptions
14 - Exceptions14 - Exceptions
14 - Exceptions
The World of Smalltalk
 
Stoop 437-proxy
Stoop 437-proxyStoop 437-proxy
Stoop 437-proxy
The World of Smalltalk
 
11 bytecode
11 bytecode11 bytecode
Stoop 301-internal objectstructureinvw
Stoop 301-internal objectstructureinvwStoop 301-internal objectstructureinvw
Stoop 301-internal objectstructureinvw
The World of Smalltalk
 
Stoop ed-inheritance composition
Stoop ed-inheritance compositionStoop ed-inheritance composition
Stoop ed-inheritance composition
The World of Smalltalk
 
Stoop 303-advanced blocks
Stoop 303-advanced blocksStoop 303-advanced blocks
Stoop 303-advanced blocks
The World of Smalltalk
 
Stoop 422-naming idioms
Stoop 422-naming idiomsStoop 422-naming idioms
Stoop 422-naming idioms
The World of Smalltalk
 
Stoop ed-subtyping subclassing
Stoop ed-subtyping subclassingStoop ed-subtyping subclassing
Stoop ed-subtyping subclassing
The World of Smalltalk
 
Stoop ed-lod
Stoop ed-lodStoop ed-lod
01 intro
01 intro01 intro

Viewers also liked (20)

Stoop 439-decorator
Stoop 439-decoratorStoop 439-decorator
Stoop 439-decorator
 
Stoop 436-strategy
Stoop 436-strategyStoop 436-strategy
Stoop 436-strategy
 
12 virtualmachine
12 virtualmachine12 virtualmachine
12 virtualmachine
 
Stoop 423-smalltalk idioms
Stoop 423-smalltalk idiomsStoop 423-smalltalk idioms
Stoop 423-smalltalk idioms
 
10 reflection
10 reflection10 reflection
10 reflection
 
05 seaside
05 seaside05 seaside
05 seaside
 
Stoop 413-abstract classes
Stoop 413-abstract classesStoop 413-abstract classes
Stoop 413-abstract classes
 
Stoop ed-class forreuse
Stoop ed-class forreuseStoop ed-class forreuse
Stoop ed-class forreuse
 
Stoop sed-class initialization
Stoop sed-class initializationStoop sed-class initialization
Stoop sed-class initialization
 
5 - OOP - Smalltalk in a Nutshell (c)
5 - OOP - Smalltalk in a Nutshell (c)5 - OOP - Smalltalk in a Nutshell (c)
5 - OOP - Smalltalk in a Nutshell (c)
 
14 - Exceptions
14 - Exceptions14 - Exceptions
14 - Exceptions
 
Stoop 437-proxy
Stoop 437-proxyStoop 437-proxy
Stoop 437-proxy
 
11 bytecode
11 bytecode11 bytecode
11 bytecode
 
Stoop 301-internal objectstructureinvw
Stoop 301-internal objectstructureinvwStoop 301-internal objectstructureinvw
Stoop 301-internal objectstructureinvw
 
Stoop ed-inheritance composition
Stoop ed-inheritance compositionStoop ed-inheritance composition
Stoop ed-inheritance composition
 
Stoop 303-advanced blocks
Stoop 303-advanced blocksStoop 303-advanced blocks
Stoop 303-advanced blocks
 
Stoop 422-naming idioms
Stoop 422-naming idiomsStoop 422-naming idioms
Stoop 422-naming idioms
 
Stoop ed-subtyping subclassing
Stoop ed-subtyping subclassingStoop ed-subtyping subclassing
Stoop ed-subtyping subclassing
 
Stoop ed-lod
Stoop ed-lodStoop ed-lod
Stoop ed-lod
 
01 intro
01 intro01 intro
01 intro
 

Similar to Stoop 390-instruction stream

Working with Bytecode
Working with BytecodeWorking with Bytecode
Working with Bytecode
Marcus Denker
 
Vlsi lab manual exp:2
Vlsi lab manual exp:2Vlsi lab manual exp:2
Vlsi lab manual exp:2
komala vani
 
Friend this-new&delete
Friend this-new&deleteFriend this-new&delete
Friend this-new&delete
Shehzad Rizwan
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
GeeksLab Odessa
 
Return of c++
Return of c++Return of c++
Return of c++
Yongwei Wu
 
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptxconstructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
AshrithaRokkam
 
Testing: ¿what, how, why?
Testing: ¿what, how, why?Testing: ¿what, how, why?
Testing: ¿what, how, why?
David Rodenas
 
Checking the Cross-Platform Framework Cocos2d-x
Checking the Cross-Platform Framework Cocos2d-xChecking the Cross-Platform Framework Cocos2d-x
Checking the Cross-Platform Framework Cocos2d-x
Andrey Karpov
 
2-Functions.pdf
2-Functions.pdf2-Functions.pdf
2-Functions.pdf
YekoyeTigabuYeko
 
AntiVirus Evasion Techniques Use of Crypters 2k14 at MundoHackerDay
AntiVirus Evasion Techniques Use of Crypters 2k14 at MundoHackerDayAntiVirus Evasion Techniques Use of Crypters 2k14 at MundoHackerDay
AntiVirus Evasion Techniques Use of Crypters 2k14 at MundoHackerDay
INCIDE
 
Stoop 300-block optimizationinvw
Stoop 300-block optimizationinvwStoop 300-block optimizationinvw
Stoop 300-block optimizationinvw
The World of Smalltalk
 
Blazing Performance with Flame Graphs
Blazing Performance with Flame GraphsBlazing Performance with Flame Graphs
Blazing Performance with Flame Graphs
Brendan Gregg
 
Introduction to C#
Introduction to C#Introduction to C#
Introduction to C#
ANURAG SINGH
 
Workshop Infrastructure as Code - Suestra
Workshop Infrastructure as Code - SuestraWorkshop Infrastructure as Code - Suestra
Workshop Infrastructure as Code - Suestra
Mario IC
 
C# 7 development
C# 7 developmentC# 7 development
C# 7 development
Fisnik Doko
 
Reactive Design Patterns: a talk by Typesafe's Dr. Roland Kuhn
Reactive Design Patterns: a talk by Typesafe's Dr. Roland KuhnReactive Design Patterns: a talk by Typesafe's Dr. Roland Kuhn
Reactive Design Patterns: a talk by Typesafe's Dr. Roland Kuhn
Zalando Technology
 
Test-Driven Infrastructure with Ansible, Test Kitchen, Serverspec and RSpec
Test-Driven Infrastructure with Ansible, Test Kitchen, Serverspec and RSpecTest-Driven Infrastructure with Ansible, Test Kitchen, Serverspec and RSpec
Test-Driven Infrastructure with Ansible, Test Kitchen, Serverspec and RSpec
Martin Etmajer
 
linq with Exampls
linq with Examplslinq with Exampls
linq with Exampls
Jitendra Gangwar
 
Pdf tech deep dive 42 paris
Pdf tech deep dive 42 parisPdf tech deep dive 42 paris
Pdf tech deep dive 42 paris
Laure Vergeron
 
C# What's next? (7.x and 8.0)
C# What's next? (7.x and 8.0)C# What's next? (7.x and 8.0)
C# What's next? (7.x and 8.0)
Christian Nagel
 

Similar to Stoop 390-instruction stream (20)

Working with Bytecode
Working with BytecodeWorking with Bytecode
Working with Bytecode
 
Vlsi lab manual exp:2
Vlsi lab manual exp:2Vlsi lab manual exp:2
Vlsi lab manual exp:2
 
Friend this-new&delete
Friend this-new&deleteFriend this-new&delete
Friend this-new&delete
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
 
Return of c++
Return of c++Return of c++
Return of c++
 
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptxconstructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
 
Testing: ¿what, how, why?
Testing: ¿what, how, why?Testing: ¿what, how, why?
Testing: ¿what, how, why?
 
Checking the Cross-Platform Framework Cocos2d-x
Checking the Cross-Platform Framework Cocos2d-xChecking the Cross-Platform Framework Cocos2d-x
Checking the Cross-Platform Framework Cocos2d-x
 
2-Functions.pdf
2-Functions.pdf2-Functions.pdf
2-Functions.pdf
 
AntiVirus Evasion Techniques Use of Crypters 2k14 at MundoHackerDay
AntiVirus Evasion Techniques Use of Crypters 2k14 at MundoHackerDayAntiVirus Evasion Techniques Use of Crypters 2k14 at MundoHackerDay
AntiVirus Evasion Techniques Use of Crypters 2k14 at MundoHackerDay
 
Stoop 300-block optimizationinvw
Stoop 300-block optimizationinvwStoop 300-block optimizationinvw
Stoop 300-block optimizationinvw
 
Blazing Performance with Flame Graphs
Blazing Performance with Flame GraphsBlazing Performance with Flame Graphs
Blazing Performance with Flame Graphs
 
Introduction to C#
Introduction to C#Introduction to C#
Introduction to C#
 
Workshop Infrastructure as Code - Suestra
Workshop Infrastructure as Code - SuestraWorkshop Infrastructure as Code - Suestra
Workshop Infrastructure as Code - Suestra
 
C# 7 development
C# 7 developmentC# 7 development
C# 7 development
 
Reactive Design Patterns: a talk by Typesafe's Dr. Roland Kuhn
Reactive Design Patterns: a talk by Typesafe's Dr. Roland KuhnReactive Design Patterns: a talk by Typesafe's Dr. Roland Kuhn
Reactive Design Patterns: a talk by Typesafe's Dr. Roland Kuhn
 
Test-Driven Infrastructure with Ansible, Test Kitchen, Serverspec and RSpec
Test-Driven Infrastructure with Ansible, Test Kitchen, Serverspec and RSpecTest-Driven Infrastructure with Ansible, Test Kitchen, Serverspec and RSpec
Test-Driven Infrastructure with Ansible, Test Kitchen, Serverspec and RSpec
 
linq with Exampls
linq with Examplslinq with Exampls
linq with Exampls
 
Pdf tech deep dive 42 paris
Pdf tech deep dive 42 parisPdf tech deep dive 42 paris
Pdf tech deep dive 42 paris
 
C# What's next? (7.x and 8.0)
C# What's next? (7.x and 8.0)C# What's next? (7.x and 8.0)
C# What's next? (7.x and 8.0)
 

More from The World of Smalltalk

05 seaside canvas
05 seaside canvas05 seaside canvas
05 seaside canvas
The World of Smalltalk
 
99 questions
99 questions99 questions
13 traits
13 traits13 traits
09 metaclasses
09 metaclasses09 metaclasses
09 metaclasses
The World of Smalltalk
 
08 refactoring
08 refactoring08 refactoring
08 refactoring
The World of Smalltalk
 
07 bestpractice
07 bestpractice07 bestpractice
07 bestpractice
The World of Smalltalk
 
06 debugging
06 debugging06 debugging
04 idioms
04 idioms04 idioms
03 standardclasses
03 standardclasses03 standardclasses
03 standardclasses
The World of Smalltalk
 
02 basics
02 basics02 basics
Stoop sed-smells
Stoop sed-smellsStoop sed-smells
Stoop sed-smells
The World of Smalltalk
 
Stoop sed-sharing ornot
Stoop sed-sharing ornotStoop sed-sharing ornot
Stoop sed-sharing ornot
The World of Smalltalk
 
Stoop sed-class initialization
Stoop sed-class initializationStoop sed-class initialization
Stoop sed-class initialization
The World of Smalltalk
 
Stoop metaclasses
Stoop metaclassesStoop metaclasses
Stoop metaclasses
The World of Smalltalk
 
Stoop ed-unit ofreuse
Stoop ed-unit ofreuseStoop ed-unit ofreuse
Stoop ed-unit ofreuse
The World of Smalltalk
 
Stoop ed-some principles
Stoop ed-some principlesStoop ed-some principles
Stoop ed-some principles
The World of Smalltalk
 
Stoop ed-frameworks
Stoop ed-frameworksStoop ed-frameworks
Stoop ed-frameworks
The World of Smalltalk
 
Stoop ed-dual interface
Stoop ed-dual interfaceStoop ed-dual interface
Stoop ed-dual interface
The World of Smalltalk
 
Stoop 450-s unit
Stoop 450-s unitStoop 450-s unit
Stoop 450-s unit
The World of Smalltalk
 
Stoop 440-adaptor
Stoop 440-adaptorStoop 440-adaptor
Stoop 440-adaptor
The World of Smalltalk
 

More from The World of Smalltalk (20)

05 seaside canvas
05 seaside canvas05 seaside canvas
05 seaside canvas
 
99 questions
99 questions99 questions
99 questions
 
13 traits
13 traits13 traits
13 traits
 
09 metaclasses
09 metaclasses09 metaclasses
09 metaclasses
 
08 refactoring
08 refactoring08 refactoring
08 refactoring
 
07 bestpractice
07 bestpractice07 bestpractice
07 bestpractice
 
06 debugging
06 debugging06 debugging
06 debugging
 
04 idioms
04 idioms04 idioms
04 idioms
 
03 standardclasses
03 standardclasses03 standardclasses
03 standardclasses
 
02 basics
02 basics02 basics
02 basics
 
Stoop sed-smells
Stoop sed-smellsStoop sed-smells
Stoop sed-smells
 
Stoop sed-sharing ornot
Stoop sed-sharing ornotStoop sed-sharing ornot
Stoop sed-sharing ornot
 
Stoop sed-class initialization
Stoop sed-class initializationStoop sed-class initialization
Stoop sed-class initialization
 
Stoop metaclasses
Stoop metaclassesStoop metaclasses
Stoop metaclasses
 
Stoop ed-unit ofreuse
Stoop ed-unit ofreuseStoop ed-unit ofreuse
Stoop ed-unit ofreuse
 
Stoop ed-some principles
Stoop ed-some principlesStoop ed-some principles
Stoop ed-some principles
 
Stoop ed-frameworks
Stoop ed-frameworksStoop ed-frameworks
Stoop ed-frameworks
 
Stoop ed-dual interface
Stoop ed-dual interfaceStoop ed-dual interface
Stoop ed-dual interface
 
Stoop 450-s unit
Stoop 450-s unitStoop 450-s unit
Stoop 450-s unit
 
Stoop 440-adaptor
Stoop 440-adaptorStoop 440-adaptor
Stoop 440-adaptor
 

Recently uploaded

From Natural Language to Structured Solr Queries using LLMs
From Natural Language to Structured Solr Queries using LLMsFrom Natural Language to Structured Solr Queries using LLMs
From Natural Language to Structured Solr Queries using LLMs
Sease
 
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
Alex Pruden
 
QA or the Highway - Component Testing: Bridging the gap between frontend appl...
QA or the Highway - Component Testing: Bridging the gap between frontend appl...QA or the Highway - Component Testing: Bridging the gap between frontend appl...
QA or the Highway - Component Testing: Bridging the gap between frontend appl...
zjhamm304
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
Edge AI and Vision Alliance
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
DianaGray10
 
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Pitangent Analytics & Technology Solutions Pvt. Ltd
 
"NATO Hackathon Winner: AI-Powered Drug Search", Taras Kloba
"NATO Hackathon Winner: AI-Powered Drug Search",  Taras Kloba"NATO Hackathon Winner: AI-Powered Drug Search",  Taras Kloba
"NATO Hackathon Winner: AI-Powered Drug Search", Taras Kloba
Fwdays
 
High performance Serverless Java on AWS- GoTo Amsterdam 2024
High performance Serverless Java on AWS- GoTo Amsterdam 2024High performance Serverless Java on AWS- GoTo Amsterdam 2024
High performance Serverless Java on AWS- GoTo Amsterdam 2024
Vadym Kazulkin
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
AstuteBusiness
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
c5vrf27qcz
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
Fwdays
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid ResearchHarnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
Neo4j
 
What is an RPA CoE? Session 2 – CoE Roles
What is an RPA CoE?  Session 2 – CoE RolesWhat is an RPA CoE?  Session 2 – CoE Roles
What is an RPA CoE? Session 2 – CoE Roles
DianaGray10
 
Christine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptxChristine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptx
christinelarrosa
 
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Neo4j
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
Javier Junquera
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
Miro Wengner
 

Recently uploaded (20)

From Natural Language to Structured Solr Queries using LLMs
From Natural Language to Structured Solr Queries using LLMsFrom Natural Language to Structured Solr Queries using LLMs
From Natural Language to Structured Solr Queries using LLMs
 
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
 
QA or the Highway - Component Testing: Bridging the gap between frontend appl...
QA or the Highway - Component Testing: Bridging the gap between frontend appl...QA or the Highway - Component Testing: Bridging the gap between frontend appl...
QA or the Highway - Component Testing: Bridging the gap between frontend appl...
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
 
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
 
"NATO Hackathon Winner: AI-Powered Drug Search", Taras Kloba
"NATO Hackathon Winner: AI-Powered Drug Search",  Taras Kloba"NATO Hackathon Winner: AI-Powered Drug Search",  Taras Kloba
"NATO Hackathon Winner: AI-Powered Drug Search", Taras Kloba
 
High performance Serverless Java on AWS- GoTo Amsterdam 2024
High performance Serverless Java on AWS- GoTo Amsterdam 2024High performance Serverless Java on AWS- GoTo Amsterdam 2024
High performance Serverless Java on AWS- GoTo Amsterdam 2024
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid ResearchHarnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
 
What is an RPA CoE? Session 2 – CoE Roles
What is an RPA CoE?  Session 2 – CoE RolesWhat is an RPA CoE?  Session 2 – CoE Roles
What is an RPA CoE? Session 2 – CoE Roles
 
Christine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptxChristine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptx
 
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
 

Stoop 390-instruction stream

  • 1. S.Ducasse 1 QuickTime™ and aTIFF (Uncompressed) decompressorare needed to see this picture. Marcus Denker denker@iam.unibe.ch Working with Bytecodes: IRBuilder and InstructionStream
  • 2. S.Ducasse 2 License: CC-Attribution-ShareAlike 2.0 http://creativecommons.org/licenses/by-sa/2.0/
  • 3. S.Ducasse 3 Reasons for working with Bytecode • Generating Bytecode • Implementing compilers for other languages • Experimentation with new language features • Parsing and Interpretation: • Analysis • Decompilation (for systems without source) • Pretty printing • Interpretation: Debugger, Profiler
  • 4. S.Ducasse 4 Overview • Squeak Bytecodes • Examples: Generating Bytecode • with IRBuilder • Decoding Bytecodes • Bytecode Execution
  • 5. S.Ducasse 5 The SqueakVirtual Machine • Virtual machine provides a virtual processor • Bytecode:The ‘machinecode’ of the virtual machine • Smalltalk (like Java): Stack machine • easy to implement interpreters for different processors • most hardware processors are register machines • SqueakVM: Implemented in Slang • Slang: Subset of Smalltalk. (”C with Smalltalk Syntax”) • Translated to C
  • 6. S.Ducasse 6 Bytecode in the CompiledMethod • CompiledMethods format: Header Literals Bytecode Trailer Pointer to Source Array of all Literal Objects Number of temps, literals... (Number>>#asInteger)inspect
  • 7. S.Ducasse 7 Bytecodes: Single or multibyte • Different forms of bytecodes: • Single bytecodes: • Example: 120: push self • Groups of similar bytecodes • 16: push temp 1 • 17: push temp 2 • up to 31 • Multibyte bytecodes • Problem: 4bit offset may be too small • Solution: Use the following byte as offset • Example: Jumps need to encode large jump offsets OffsetType 4bits 4bits
  • 8. S.Ducasse 8 Example: Number>>asInteger • Smalltalk code: • Symbolic Bytecode Number>>asInteger "Answer an Integer nearest the receiver toward zero." ^self truncated 9 <70> self 10 <D0> send: truncated 11 <7C> returnTop
  • 9. S.Ducasse 9 Example: Step by Step • 9 <70> self • The receiver (self) is pushed on the stack • 10 <D0> send: truncated • Bytecode 208: send litereral selector 1 • Get the selector from the first literal • start message lookup in the class of the object that is top of the stack • result is pushed on the stack • 11 <7C> returnTop • return the object on top of the stack to the calling method
  • 10. S.Ducasse 10 Squeak Bytecodes • 256 Bytecodes, four groups: • Stack Bytecodes • Stack manipulation: push / pop / dup • Send Bytecodes • Invoke Methods • Return Bytecodes • Return to caller • Jump Bytecodes • Control flow inside a method
  • 11. S.Ducasse 11 Stack Bytecodes • push and store, e.g. temps, instVars, literals • e.g: 16 - 31: push instance variable • Push Constants (False/True/Nil/1/0/2/-1) • Push self, thisContext • duplicate top of stack • pop
  • 12. S.Ducasse 12 Sends and Returns • Sends: receiver is on top of stack • Normal send • Super Sends • Hard-coded sends for efficiency, e.g. +, - • Returns • Return top of stack to the sender • Return from a block • Special bytecodes for return self, nil, true, false (for efficiency)
  • 13. S.Ducasse 13 Jump Bytecodes • Control Flow inside one method • Used to implement control-flow efficiently • Example: 9 <76> pushConstant: 1 10 <77> pushConstant: 2 11 <B2> send: < 12 <99> jumpFalse: 15 13 <20> pushConstant: 'true' 14 <90> jumpTo: 16 15 <73> pushConstant: nil 16 <7C> returnTop ^ 1<2 ifTrue: ['true']
  • 14. S.Ducasse 14 What you should have learned... • ... dealing with bytecodes directly is possible, but very boring. • We want reusable abstractions that hide the details (e.g. the different send bytecodes) • We would like to have frameworks for • Generating bytecode easily • Parsing bytecode • Evaluating bytecode
  • 15. S.Ducasse 15 Generating Bytecodes • IRBuilder • Part of the new compiler (on SqueakMap) • Like an Assembler for Squeak
  • 16. S.Ducasse 16 IRBuilder: Simple Example • Number>>asInteger iRMethod := IRBuilder new rargs: #(self); "receiver and args" pushTemp: #self; send: #truncated; returnTop; ir. aCompiledMethod := iRMethod compiledMethod. aCompiledMethod valueWithReceiver:3.5 arguments: #()
  • 17. S.Ducasse 17 IRBuilder: Stack Manipulation • popTop - remove the top of stack • pushDup - push top of stack on the stack • pushLiteral: • pushReceiver - push self • pushThisContext
  • 18. S.Ducasse 18 IRBuilder: Symbolic Jumps • Jump targets are resolved: • Example: false ifTrue: [’true’] ifFalse: [’false’] iRMethod := IRBuilder new rargs: #(self); "receiver and args" pushLiteral: false; jumpAheadTo: #false if: false; pushLiteral: 'true'; "ifTrue: ['true']" jumpAheadTo: #end; jumpAheadTarget: #false; pushLiteral: 'false'; "ifFalse: ['false']" jumpAheadTarget: #end; returnTop; ir.
  • 19. S.Ducasse 19 IRBuiler: InstanceVariables • Access by offset • Read: getField: • receiver on top of stack • Write: setField: • receiver and value on stack • Example: set the first instance variable to 2 iRMethod := IRBuilder new rargs: #(self); "receiver and args declarations" pushLiteral: 2; pushTemp: #self; setField: 1; pushTemp: #self; returnTop; ir. aCompiledMethod := iRMethod compiledMethod. aCompiledMethod valueWithReceiver: 1@2 arguments: #()
  • 20. S.Ducasse 20 IRBuilder:TemporaryVariables • Accessed by name • Define with addTemp: / addTemps: • Read with pushTemp: • Write with storeTemp: • Examle: set variables a and b, return value of a iRMethod := IRBuilder new rargs: #(self); "receiver and args" addTemps: #(a b); pushLiteral: 1; storeTemp: #a; pushLiteral: 2; storeTemp: #b; pushTemp: #a; returnTop; ir.
  • 21. S.Ducasse 21 IRBuilder: Sends • normal send • super send • The second parameter specifies the class were the lookup starts. .... builder send: #selector toSuperOf: aClass; builder pushLiteral: ‘hello’ builder send: #size;
  • 22. S.Ducasse 22 IRBuilder: Lessons learned • IRBuilder: Easy bytecode generation • Not part of Squeak yet • Will be added to Squeak 3.9 or 4.0 • Next: Decoding bytecode
  • 23. S.Ducasse 23 Parsing and Interpretation • First step: Parse bytecode • enough for easy analysis, pretty printing, decompilation • Second step: Interpretation • needed for simulation, complex analyis (e.g., profiling) • Squeak provides frameworks for both: • InstructionStream/InstructionClient (parsing) • ContextPart (Interpretation)
  • 24. S.Ducasse 24 The InstructionStream Hierarchy InstructionStream ContextPart BlockContext MethodContext Decompiler InstructionPrinter InstVarRefLocator BytecodeDecompiler
  • 25. S.Ducasse 25 InstructionStream • Parses the byte-encoded instructions • State: • pc: programm counter • sender: the method (bad name!) Object subclass: #InstructionStream instanceVariableNames: 'sender pc' classVariableNames: 'SpecialConstants' poolDictionaries: '' category: 'Kernel-Methods'
  • 26. S.Ducasse 26 Usage • Generate an instance: • Now we can step through the bytecode with • calls methods on a client object for the type of bytecode, e.g. • pushReceiver • pushConstant: value • pushReceiverVariable: offset instrStream := IntructionStream on: aMethod instrStream interpretNextInstructionFor: client
  • 27. S.Ducasse 27 InstructionClient • Abstract superclass • Defines empty methods for all methods that InstructionStream calls on a client • For convienience: • Client don’t need to inherit from this Object subclass: #InstructionClient instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Kernel-Methods'
  • 28. S.Ducasse 28 Example:A test InstructionClientTest>>testInstructions "just interpret all of methods of Object" | methods client scanner| methods := Object methodDict values. client := InstructionClient new. methods do: [:method | scanner := (InstructionStream on: method). [scanner pc <= method endPC] whileTrue: [ self shouldnt: [scanner interpretNextInstructionFor: client] raise: Error. ]. ].
  • 29. S.Ducasse 29 Example: Printing Bytecodes • InstructionPrinter: Print the bytecodes as human readable text • Example: print the bytecode of Number>>asInteger: String streamContents: [:str | (InstructionPrinter on: Number>>#asInteger) printInstructionsOn: str ] result: '9 <70> self 10 <D0> send: truncated 11 <7C> returnTop '
  • 30. S.Ducasse 30 InstructionPrinter • Class Definition: InstructionClient subclass: #InstructionPrinter instanceVariableNames: 'method scanner stream oldPC indent' classVariableNames: '' poolDictionaries: '' category: 'Kernel-Methods'
  • 31. S.Ducasse 31 InstructionPrinter • Main Loop: InstructionPrinter>>printInstructionsOn: aStream "Append to the stream, aStream, a description of each bytecode in the instruction stream." | end | stream := aStream. scanner := InstructionStream on: method. end := method endPC. oldPC := scanner pc. [scanner pc <= end] whileTrue: [scanner interpretNextInstructionFor: self]
  • 32. S.Ducasse 32 InstructionPrinter • Overwrites methods form InstructionClient to print the bytecodes as text • e.g. the method for pushReceiver: InstructionPrinter>>pushReceiver "Print the Push Active Context's Receiver on Top Of Stack bytecode." self print: 'self'
  • 33. S.Ducasse 33 Example: InstVarRefLocator InstructionClient subclass: #InstVarRefLocator instanceVariableNames: 'bingo' .... interpretNextInstructionUsing: aScanner bingo := false. aScanner interpretNextInstructionFor: self. ^bingo popIntoReceiverVariable: offset bingo := true pushReceiverVariable: offset bingo := true storeIntoReceiverVariable: offset bingo := true
  • 34. S.Ducasse 34 InstVarRefLocator • CompiledMethod>>#hasInstVarRef hasInstVarRef "Answer whether the receiver references an instance variable." | scanner end printer | scanner := InstructionStream on: self. printer := InstVarRefLocator new. end := self endPC. [scanner pc <= end] whileTrue: [ (printer interpretNextInstructionUsing: scanner) ifTrue: [^true]. ]. ^false
  • 35. S.Ducasse 35 InstVarRefLocator • Example for a simple bytecode analyzer • Usage: aMethod hasInstVarRef (TestCase>>#debug) hasInstVarRef true (Integer>>#+) hasInstVarRef false
  • 36. S.Ducasse 36 Example: Decompiling to IR • BytecodeDecompiler • Usage: InstructionStream subclass: #BytecodeDecompiler instanceVariableNames: 'irBuilder blockFlag' classVariableNames: '' poolDictionaries: '' category: 'Compiler-Bytecodes' BytecodeDecompiler new decompile: (Number>>#asInteger)
  • 37. S.Ducasse 37 Decompiling • uses IRBuilder for building IR • e.g. code for the bytecode pushReceiver: BytecodeDecompiler>>pushReceiver irBuilder pushReceiver
  • 38. S.Ducasse 38 ContextPart: Execution Semantics • Sometimes we need more than parsing • “stepping” in the debugger • system simulation for profiling InstructionStream subclass: #ContextPart instanceVariableNames: 'stackp' classVariableNames: 'PrimitiveFailToken QuickStep' poolDictionaries: '' category: 'Kernel-Methods'
  • 39. S.Ducasse 39 Simulation • Provides a complete Bytecode interpreter • Run a block with the simulator: (ContextPart runSimulated: [3 factorial])
  • 40. S.Ducasse 40 Profiling: MesageTally • Usage: • Other example: MessageTally tallySends: [3 factorial] This simulation took 0.0 seconds. **Tree** 1 SmallInteger(Integer)>>factorial 1 SmallInteger(Integer)>>factorial 1 SmallInteger(Integer)>>factorial 1 SmallInteger(Integer)>>factorial MessageTally tallySends: [’3’ + 1] **Leaves** 4 SmallInteger(Integer)>>factorial 3 SmallInteger(Integer)>>factorial 1 BlockContext>>DoIt