Monthly Archives: May 2011

Introduction to Smalltalk bytecodes

Hi all. It this post I will give you a quick overview and introduction to bytecodes. I won’t talk that much because this topic is well explained in the Blue book, in the code, etc. In the previous posts we saw that a CompiledMethod is all about bytecodes and literals (ok, and a header and a trailer). To really follow the post, I recommend you to have an image with VMMaker. If you don’t know how to do it, please see the title “Prepare the image” of a previous post.

Bytecodes introduction

Let’s start from the beginning: What is a bytecode?  A bytecode is a compact and platform neutral representation of machine code instructions, interpreted by VM. When you code and then save a method in Smalltalk, the Compiler generates an instance of CompiledMethod. Your method’s code is decomposed by the Compiler into a set of basic instructions so that the VM can interpret them.

We have also seen that a CompiledMethod is just an array of bytes. And “BYTEcode” has the prefix “byte”. So, as you can imagine, every bytecode is represented by a byte. One bytecode, one byte (sure?? mmmm). One byte, 8 bits, 2^8 -1 = 255 possible different bytecodes.

Imagine that we code the following basic method:

MyClass >> foo
self name.

To see the bytecodes there are two possibilities: print the answer of  the message #symbolic to the CompiledMethod instance. For example, (MyClass >> #foo) symbolic or use the SystemBrowser, button “View” -> “byte codes”. The bytecodes from the previous method are:

17 <70> self
18 <D0> send: name
19 <87> pop
20 <78> returnSelf

So…how do we interpret such symbolic representation?

Understanding bytecodes printing

Let’s start from left to right. First “column” is a number. In this case, from 17 to 20. What do those number mean?  Explore or inspect the CompiledMethod:

So, those number represent just the position in the whole array. We said a CM (CompiledMethod) was an array of bytes. So, those number represent the position. The CM has two regions: the literal frame (the first bytes of the CM where the literals are stored) and the bytecodes. These numbers are called “Program Counter” (PC) when they are in the bytecode part. For example, if we send the message #endPC to this CM instance, we will get 20 which is the last byte of the CM that represents bytecodes. The next one, 21, is already representing the trailer. The same way, #initialPC answers 17. And how those two methods are implemented?  the #initialPC uses the header’s encoded information such as the number of literals. And #endPC delegates to its trailer since he knows the size of the trailer.

The second column is an hexadecimal surrounded by <> which represents the bytecode number. For example, <70>,, etc. This hexadecimal represent the unique number of bytecode. ’70’ is the bytecode push receiver, ‘D0’ is a send bytecode, 85 pop stack, and push receiver. Since these numbers are encoded in 1 byte it follows that there are 255 possible differnt type of bytecodes.

The third column is just a text describing the type of bytecode.

If we analyze now the bytecodes generated for our simple method that does a “self name” we have that:  the first bytecode (number 17) it just pushes the receiver (self) into the stack. We need that in the stack because in the next bytecode we send a message to it. The second bytecode, 18, sends the message #name to what it is in the stack. When this bytecode finishes, it pushes in the stack the result of the send. But our method doesn’t do anything with it and instead it just answers self (because there is not explicit return). So, we need to do a pop first, bytecode number 19, to remove the result from stack and let the receiver in the top of the stack. And now, we can finally do the return with bytecode number 20.

Mapping bytecodes from image side to VM side

So far we saw how the bytecodes in the CM look like, but we didn’t see how they are map to the VM. So, take your image with VMMaker loaded, and inspect the method #initializeBytecodeTable. You will see that such method is something like this:

The table follows much more but I cut it for the post. So as you see it is just a table that maps numbers to methods 😉  We saw that the symbolic representation has 3 columns, and the second one which was surrounded by <> and an hexadecimal value represents the number of the bytecode. That number is exactly this one used in this table, with the difference that it is in decimal. So, for example the bytecode “<78> returnSelf”, if we translate 78 from hexa to decimal (just print 16r78)  we get 120, which maps to the method #returnReceiver. So, you can now just browse the method and look what it does 🙂  Remember that this is part of VMMaker and this code is written is SLANG. For more details read my old posts.

StackInterpreter >> returnReceiver
localReturnValue := self receiver.
self commonReturn

You have now learned how to see the bytecodes of a method and how to see its implementation in the VM. Cool!!  You deserve a break (or a beer) 🙂

Did you notice that some bytecodes are mapped directly to one only number (like #returnReceiver) but some other like #pushLiteralVariableBytecode are mapped to a range of numbers?  We will see later why.

More complicated bytecodes

Now, let’s see a more advance method, for example, this one:

fooComplicated: aBool and: aNumber
| something aName |
aName := self name.
Transcript show: aName.
aBool
ifTrue: [ ^ aName ].
^ nil

Which generates the following bytecodes:

25 <70> self
26  send: name
27 <6B> popIntoTemp: 3
28 <42> pushLit: Transcript
29 <13> pushTemp: 3
30  send: show:
31 <87> pop
32 <10> pushTemp: 0
33 <99> jumpFalse: 36
34 <13> pushTemp: 3
35 <7C> returnTop
36 <7B> return: nil

There are a couple of new bytecodes in this method. Bytecode 27, does a pop of the return of “self name” and push it in the temp number 3. Notice that temps are both, parameters and temp variables. In this case, temp 0 is ‘aBool’, temp 1 ‘aNumber’, temp 2 ‘something’ and temp 3 is ‘aName’. Bytecode 28 needs to push the literal “Transcript” into the stack since in the next bytecode a message is sent to it. Bytecode 29 pushes ‘aName’ to the stack since it will be the parameter for the send.  Bytecode 30 does the send and 31 does a pop because we don’t do anything with the return of the message.

With bytecode 32 we put ‘aBool’ into the stack and then….then…shouldn’t we have something like 33 send: ifTrue:ifFalse:  ???  Yes, we should. But the compiler does an optimization and replaces the message send by a jump bytecode. In this case, a jump bytecode saying that when it is false jump to bytecode number 36 which does the return nil. Otherwise (if true), continue with bytecode 34 which pushes ‘aName’ into the stack and finally bytecode 35 does the return of the top of the stack (where we can ‘aName’).

How do we represent parameters in bytecodes?

We shouldn’t forget that btyecodes are just a number between 0 and 255. The bytecode <78> returnSelf  is number 120, which was we can see in #initializeBytecodeTable it is mapped by  (120 returnReceiver). Does this method requires any kind of parameter? No. It just returns the receiver. Now,  let’s analyze the bytecode <6B> popIntoTemp: 3 from the previous example. 16r6B -> 107.  Ok, cool. So, number 107 does a pop and puts that into the temp number 3. But….all what we have in the CompiledMethod is the bytecode, the byte that contains the number 107. Nothing more. Imagine the method in the VM that is mapped to this bytecode….how can it knows the temp number?   The same with bytecode “<42> pushLit: Transcript”. It is just a number,  66. Where is the “Transcript” stored?

So…the generic question is, if we only have a bytecode number, how do we solve the bytecodes that require some parameters ? Ok, this will sound a little weird. Or smart?  The truth is that this missing information is sometimes (we will see later why sometimes) encoded using offsets in the range of bytecodes. Let’s see the example of the  <6B> popIntoTemp: 3, which is bytecode number 107. In #initializeBytecodeTable, we can see: “(104 111 storeAndPopTemporaryVariableBytecode)“. So we have a range of bytecode between 104 and 111. In this case we want to do a pop and put the result in the temp number 3. If we can assume that 104 is for temp 0, 105, temp1, 106 temp2 and 107 temp3 🙂 we now understand why out bytecode number is 107. That bytecode number encodes that the number of the temp is the 3. The method storeAndPopTemporaryVariableBytecode  will be able to get a diff between the current number (107) and the start of this range (104) and finally know that the temp number is the 3th.

The same happens with the other example <42> pushLit: Transcript, number 66. In #initializeBytecodeTable we can see “( 64  95 pushLiteralVariableBytecode)“. 64 is for literal at 1, 65 at 2, and 66 at 3.   Now, do (MyClass >> #fooComplicated:and:) literalAt: 3 -> #Transcript->Transcript  🙂

Now, if we analyze “(104 111 storeAndPopTemporaryVariableBytecode)” we can understand that the maximum amount of temporal variable is 7 (111-104). However, in this post, we saw the class comment of CompiledMethod says “(index 18)    6 bits:    number of temporary variables (#numTemps)”. That means that maximum number of temps is 2^6-1=63 . So…..something is wrong. Let’s find out what.

Extended bytecodes

(104 111 storeAndPopTemporaryVariableBytecode)”  supports 7 temps, but CompiledMethod class comment says 63 are supported. So, let’s create a method with more than 7 temps and let’s see its bytecodes. If we continue with our example we now modify the method to this:

fooComplicated: aBool and: aNumber
| something aName a b c d e f g h i j k |
d := self name.
Transcript show: aName.
aBool
ifTrue: [ ^ aName ].
^ nil

In this case, “d := self name” we are assigning ‘name’ to ‘d’ which is the temp number 7 (remember they start in 0 and the parameters are count together with the temp variables). Hence, the bytecodes are:

 25 <70> self
 26  send: name
 27 <6F> popIntoTemp: 7
 28 <42> pushLit: Transcript
 29 <13> pushTemp: 3
 30  send: show:
 31 <87> pop
 32 <10> pushTemp: 0
 33 <99> jumpFalse: 36
 34 <13> pushTemp: 3
 35 <7C> returnTop
 36 <7B> return: nil

Now, if we just change “d := self name.” to “e := self name.” we would be using the parameter number 8. What would happen? Ok, if you change it you will see that the bytecode changes from “27 <6F> popIntoTemp: 7” to “27 <82 48> popIntoTemp: 8”. Chan! Chan! Chan! What is that???? It seems the bytecode is using in fact 2 bytecodes? (82 and 48).

These kind of bytecodes are called “extended bytecodes”. If we check in #initializeBytecodeTable bytecode 16r82 = 130 is #extendedStoreAndPopBytecode. So at least we know which method is it. Now, what does the 2 bytecode mean (48 in our example) ?  Somehow such second byte should tell us the number of the temp (8 in our example). If we do 16r48 = 72 and check the bytecode 72 we get it is #pushLiteralVariableBytecode, which doesn’t seem to be correct. So, this second byte does not represent a bytecode. Instead, it represents just a byte that encodes information. That information is usually a type and an index, both encoded in one single byte.

In this particular example of #extendedStoreAndPopBytecode uses 2 bits for a type and 6 bits for an index:

extendedStoreBytecode
| descriptor variableType variableIndex association |
<inline: true>
descriptor := self fetchByte.
self fetchNextBytecode.
variableType := descriptor >> 6 bitAnd: 3.
variableIndex := descriptor bitAnd: 63.
variableType = 0 ifTrue:
[^objectMemory storePointer: variableIndex ofObject: self receiver withValue: self internalStackTop].
variableType = 1 ifTrue:
[^self temporary: variableIndex in: localFP put: self internalStackTop].
variableType = 3 ifTrue:
[association := self literal: variableIndex.
^objectMemory storePointer: ValueIndex ofObject: association withValue: self internalStackTop].
self error: 'illegal store'.
^nil

We can see that in our example, 16r48 = 72.  (72 >> 6) bitAnd: 3  -> 1. So, type is 1. The 3 is because it uses 2 bits for the type (2^2-1=3). And 72 bitAnd: 63 -> 8  (which correctly is the number of temp we need). 63 is because 2^6-1=63.  As you can notice, each bytecode is responsible of decoding the information of the second byte. The compiler of course, needs to correctly generate the bytecodes. #extendedStoreAndPopBytecode was an example so that you can understand and learn, but there are much more extended bytecodes. There are even “single extended bytecodes” and “double extended bytecodes”.

Why do we need extended bytecodes?

Well, I am not an expert at all in this subject but I can guess it is because of the size of CompiledMethod. In the previous example of the extended bytecode, it uses two bytes instead of one, as we can see in the explorer:

Notice that bytecode number 27 occupies two (28 is not shown). At the beginning we saw that when we have a “range” in the bytecodes it means that the difference encodes a number, usually an index. But if we need a range of bytecodes for the maximum supported, we would need much more than 255. Hence, more bytes per bytecode.  Since most methods in Smalltalk are short and encode few number of instance variables, parameters, temporal variables, etc, it was decided to use 255 and just use more bytes per bytecode for those cases that was needed. For example:

(CompiledMethod allInstances select: [:each | each numTemps > 7]) size  -> 1337
CompiledMethod instanceCount -> 75786
((1337 * 100) / 75786) asFloat -> 1.7641780803842397

So…only a 1.76% of the CompiledMethod of my image have more than 7 temporal variables. And remember that this was just an example, but there are extended bytecodes for more things. Maybe (I have no idea) with today computers this is not worth it and maybe having 3 or 4 bytes for every bytecode is enough. But since it is like this and working correctly, why to change it?

Groups of bytecodes

Since the specification of the blue book of Smalltalk-80, bytecodes are known to be grouped in different groups. And since the core of Squeak/Pharo VM is implemented in a subset of Smalltalk called SLANG and since we have classes with methods that represents Interpreters….how would these groups be represented? Of course, as method categories!!! So, you can map each of the following group, with a method category of an Interpreter class:

  • Stack manipulation bytecodes: all things related to push and pop.
  • Message sending bytecodes: bytecodes that are used when sending messages.
  • Return bytecodes: are used for different kinds of return.
  • Jump bytecodes are related to conditionals

Look the attached screenshot:

Books and links

In this post it is easy: just read the blue book 🙂   As always, you can download it in pdf from http://stephane.ducasse.free.fr/FreeBooks.html or directly browse the web version provided by Eliot Miranda. For a bytecode introduction read the end of chapter 26  and for more details the whole chapter 28. Notice that the specification has changed a bit from the 80’s and there are now there are more bytecodes but the general idea is still valid.


Playing with CompiledMethod

The today’s stop of this Journey through the VM is about CompiledMethods. In the previous post I explained the different class formats and specially, the unique format of CompiledMethod. Today we are going deeper with them and we will see why they are even more special 😉

Summary of the previous post: CompiledMethod instances are internally represented in the VM as bytes. However, CompiledMethod is the only class in the system that mixes pointers (for the literals) with bytes (for the bytecodes). So those bytes encodes both things.

Inspecting a CompiledMethod

What is the normal way to learn something in Smalltalk? Open your image and check senders, references, or someone who does more or less what you need and try to understand it. In the previous post, I showed you how inspecting or exploring a CompiledMethod give us a lot useful information like the header, the literals, the bytecodes and the trailer. Example:

So this means that at least the Inspector and the Explorer can have access to the CompiledMethod and understand its internal. Let’s take the Inspector (we could have taken also the explorer in which case take a look to CompiledMethod >> #explorerContents). When we inspect a CompiledMethod, the inspector class that is used is CompiledMethodInspector. So, first point, there is a special inspector class for CompiledMethod. Otherwise, if we inspect it with a normal inspector, for example if we do “BasicInspector openOn: (MyClass >> #testSomething)” we have something like this:

CompiledMethodInspector has two important methods:

CompiledMethodInspector >> fieldList

| keys |
keys := OrderedCollection new.
keys add: 'self'.
keys add: 'all bytecodes'.
keys add: 'header'.
1 to: object numLiterals do: [ :i |
keys add: 'literal', i printString ].
object initialPC to: object size do: [ :i |
keys add: i printString ].
^ keys asArray
CompiledMethodInspector  >> selection

| bytecodeIndex |
selectionIndex = 0 ifTrue: [^ ''].
selectionIndex = 1 ifTrue: [^ object ].
selectionIndex = 2 ifTrue: [^ object symbolic].
selectionIndex = 3 ifTrue: [^ object headerDescription].
selectionIndex <= (object numLiterals + 3)
ifTrue: [ ^ object objectAt: selectionIndex - 2 ].
bytecodeIndex := selectionIndex - object numLiterals - 3.
^ object at: object initialPC + bytecodeIndex - 1

So…as you can see in the code, “keys add: ‘all bytecodes’.”  maps to “selectionIndex = 2 ifTrue: [^ object symbolic].“, and “keys add: ‘header’.” to “selectionIndex = 3 ifTrue: [^ object headerDescription].“.  What we should learn from this, is that CompiledMethod >> #symbolic answers a string which nicely shows the bytecodes. So for example, if we have the method:

MyClass >> testSomething
TestCase new.
self name.
Transcript show: 'The answer is:', 42.

Then, “(MyClass >> #testSomething) symbolic” answers the following:

41 <40> pushLit: TestCase
42  send: new
43 <87> pop
44 <70> self
45  send: name
46 <87> pop
47 <43> pushLit: Transcript
48 <25> pushConstant: ''The answer is:''
49 <26> pushConstant: 42
50  send: ,
51  send: show:
52 <87> pop
53 <78> returnSelf

Don’t worry for the moment about the first number in each column (for the interested guys it is the PC -> program counter) and the hexadecimal between <>  (it is the bytecode number in hexa). I will explain that in a future post.

This method #symbolic could be the same used by the SystemBrowser when you select “View” -> “Bytecodes”.  From the previous example, we can also learn that CompiledMethod implements methods like #numLiterals, #objectAt:, #initialPC, etc.  Imagine the CompiledMethod as an array of bytes…how can you determinate which part is literals and which one is bytecodes?  How the #numLiterals can be implemented in CompiledMethod if it is just an array of bytes?

CompiledMethod header

It may be already obvious that CompiledMethods have a header. But be careful, CompiledMethod have both, the normal object header every object has, and then a special header which is just the first word (32 bits -> 4 bytes) of the byte array. So this header is just before the literals and the bytecodes. As we can read in the class comment of CompiledMethod:

“The header is a 30-bit integer with the following format:

(index 0)    9 bits:    main part of primitive number   (#primitive)
(index 9)    8 bits:    number of literals (#numLiterals)
(index 17)    1 bit:    whether a large frame size is needed (#frameSize)
(index 18)    6 bits:    number of temporary variables (#numTemps)
(index 24)    4 bits:    number of arguments to the method (#numArgs)
(index 28)    1 bit:    high-bit of primitive number (#primitive)
(index 29)    1 bit:    flag bit, ignored by the VM  (#flag)”

Ok, with this comment you may notice the limits imposed in methods. For example, 9 bits for a primitive it means (2^9) -1=511. BTW, I think this class comment is outdated and now there are 11 bits for primitive index, so it is (2^11) – 1 = 2 047. But you get the idea…. anyway, it is not likely that you have ever reached any of these limits.

Who is responsable of generating such header in the CompiledMethod?  In this post, I told you that usually the input for the Compiler was a string representing the source code and the result was a CompiledMethod instance. Hence, the Compiler takes care about creating such CompiledMethod header. Notice that this header is not only used from the image side but also from the VM. Check (in the VMMaker) implementors and senders of #argumentCountOf:, #literal:ofMethod:, #primitiveIndexOf:, #tempCountOf:, etc.

CompiledMethod trailer

Something you should be asking yourself is where the source code is stored?  I mean, when you open a browser and see the source code of a method, where does it come from?  because in the CompiledMethod we saw that only literals and bytecodes are stored, not source code. So???  Ok… the source code is stored in two files: .sources and .changes. The “old” methods’ source code is in the .sources file and the “new” method’s source code in the .changes. You can browse #condenseChanges and #condenseSources for details. So far so good. But…. how a CompiledMethod instance is map to its source code in the file?  Excellent question Mariano 🙂

The same way there is a special header for CompiledMethod, there is a trailer. So far the trailer has been used only for getting the source code of the method. Some time ago, this trailer was one word size (4 bytes) and it encoded a number which was the offset in the .sources/.changes file. That number represent both things: the offset in the file, and a flag to say from which file (if .changes or .sources). Check for example the method #filePositionFromSourcePointer:. In addition, the logic of encoding and decoding the trailer was implemented in the CompiledMethod class.

In today’s Pharo images (and Squeak), this is not true anymore. There are two big differences with the “old” approach:

  1. The trailer was reified with the class CompiledMethodTrailer.
  2. There are different kind of trailers implemented and up to 255 possibilities. The implemented kinds are: normal source pointer, temp names (the decompiler can use such temp names when getting the source so that to generate a source code more similar to the original one), variable length (for example when .changes is bigger than 32MB), etc. For more details, check #trailerKinds. Of course, the most common type is “SourcePointer”.

CompiledMethod is a chunk of bytes (this is why it is a subclass from ByteArray), and its format is “bytes”, so it means it cannot define normal instance variables.  So how can it have a CompiledMethodTrailer?  Ok, it works this way: when a CompiledMethod is being created (usually by the Compiler), a specific CompiledMethodTrailer instance is also created. That instance of CompiledMethodTrailer has to be created with a specific type (source pointer, temp names, etc). Once the CompiledMethod is almost ready the trailer instance is encoded as bytes in the CompiledMethod instance, and then it is garbage collected. Later on, when someone ask to the CompiledMethod for its source code (using the method #getSource), it delegates to a trailer instance. But there is not trailer instance as this moment. So….every time the source code is needed, the CompiledMethod creates an instance of a trailer. But notice that it is up to the CompiledMethodTrailer to know how many bytes are the trailer, how to decode it and what do the bytes represent (if a source pointer, an array of temp names, etc). Finally, the trailer answers the source code of the method. So, the CompiledMethod just has:

CompiledMethod >> trailer
"Answer the receiver's trailer"
^ CompiledMethodTrailer new method: self

The CompiledMethodTrailer just read the last byte, it checks in an internal table to see which kind of trailer is it, and then perform the correct method to decode the information. The amount of bytes used by the trailer and what they represent, depends on the kind of trailer.

method: aMethod

| flagByte |

data := size := nil.
method := aMethod.
flagByte := method at: (method size).

"trailer kind encoded in 6 high bits of last byte"
kind := self class trailerKinds at: 1+(flagByte>>2).

"decode the trailer bytes"
self perform: ('decode' , kind) asSymbol.

"after decoding the trailer, size must be set"
[size notNil] assert.

Depending on the type of trailer,  CompiledMethodTrailer will finally execute one of the methods encode* when the CompiledMethod is being created, and decode* when asking its source code.

A question to all of you….wouldn’t it make sense to rename CompiledMethodTrailer to MethodSource ? because trailers has been always use only for that….

Decompiling CompiledMethods

Why source code is not stored in CompiledMethod? From my point of view, there are 2 main reasons:

  1. Because as its class name suggests, they reify COMPILED methods, not source methods or whatever name you want to use.
  2. Memory and security reasons. When you deploy an application written in C, do you include source code? no. And in Java? no. So why we would do it in Smalltalk? Remember that the way to “deploy” a Smalltalk application is providing an .image.

The ideal approach would be to have the sources in development and to be able to remove them when deploying. Smalltalk allows us that. Just remove the .sources file and that’s all 🙂 Your image continues to work as if nothing has happened. But sometimes we have a bug in our application and we want to be able to browse the code. Guess what? Smalltalk provides that also 😉  Let’s try it (don’t try in Pharo1.3 because there is a bug. Use anyone before 1.3). Create a method anywhere, for example:

testSomething: aaa with: bbb and: ccc
| name |
TestCase new.
(4 = 3)
ifTrue: ["I am a nice comment, don't remove meeee pleaeee!"]
ifFalse: ["I like this way of formatting my code"].

name := self name.
Transcript show: 'The answer is:', 42.

Now, close your image. Rename the .changes file (creating a new method will ensure that the source pointer points to the .changes and not to .sources) so that it is not found. Open your image again, and you may have the popup saying that the .changes couldn’t be find. No problem. Accept it.

Now, if you open the system browser, you can browse any method of the image. And only whose source were in the .changes will look similar to this:

testSomething: t1 with: t2 and: t3
| t4 |
TestCase new.
4 = 3.
t4 := self name.
Transcript show: 'The answer is:' , 42

What you are seeing is not the source code of the method but instead the decompiled one. The compiler is able to decompile a CompiledMethod (using the bytecodes and literals) and get the possible “source code”. However, the decompiler source is not exactly the same as the original source. Note that the decompiler the only thing it has for a method is the bytecodes and the literals. Hence, the decompiled code does not have:

  • Temporal variable and parameters  names. Since they are not stored in the CompiledMethod they are lost. Both temps and parameters are replaced in the decompiled code with “t1”, “t2”, etc.
  • Comments are lost (they are not stored in the CompiledMethod).
  • Code formatting (tabs and spaces) is lost.

The cool thing is that even with the decompiled code we can get an idea of the code, debug it, and probably find the bug we were looking for.

Notice that the source code of “old” methods are stored not in the .changes but in the .sources. So, even removing .changes there are methods which get the source from the .sources file. Therefore, we can also remove the .sources and that way all methods in the image will be decompiled if you try to browse them.

Depending of what and where you are deploying, getting rid of .sources and .changes could be worth it.

CompiledMethod equality

What do you expect the following expression to answer:

(Boolean>>#&) = (Boolean>>#|)

Ok…you need to see the source code?

& aBoolean
"Evaluating conjunction. Evaluate the argument. Then answer true if
both the receiver and the argument are true."

self subclassResponsibility
| aBoolean
"Evaluating disjunction (OR). Evaluate the argument. Then answer true
if either the receiver or the argument is true."

self subclassResponsibility

So? true or false? TRUEEEE!!! that is true. And why? if they have different comments, they have different selectors! So? who cares about that? we are talking about COMPILED methods. Are the bytecodes the same? yes. Are the literals the same? yes.  So they are the same compiled method. Point. So….you would really be careful when putting CompiledMethods in Sets, Dictionaries or things like that. Example:

InstructionClient methods size -> 27
InstructionClient methods asSet size -> 21

Conclusion: use an IdentitySet or a IdentiyDictionary if you want to avoid problems.

Sorry for the long post, but there is too much to talk about CompiledMethods. In the next post we will talk a little more about bytecodes.


Class formats and CompiledMethod uniqueness

Before going deeper with CompiledMethods I would like to talk a little bit about class formats. Unfortunately, I didn’t find class formats documented more than in code and method comments. If you know a source of documentation of this topic, please let me know.

Class format

From my point of view, the class format is a really internal and implementative detail of the VM. The class format defines the structure (layout) of the instances of a class, in the VM. In the previous post, I said: “In the internal representation of the Virtual Machine, objects are a chunck of memory. They have an object header which (there will be a whole post about it) can be between one and three words, and following the object header, there are slots (normally of 32 or 64 bytes) that are memory addresses which usually (we will see why I didn’t say always) represent the instance variables.”

So, usually, that is, “normal” structure, an object has a fixed amount of instance variables which are just pointers to other objects. In this case, those “slots” (which are one word size, that is 32 or 64 bits) contain the memory address (pointer) of the header of the object they point to. But that’s not the only possibility, another object (like a Collection instance), do not have a fixed number of instance variables, but instead it is variable. And the representation is not always pointers (a word), but it can also be bytes. In summary, what changes is how it is represented the chunk of memory of an object.

Different class formats

  • Normal: there is a fixed amount of instance variables and each of them is just a pointer to another object. Notice that not only the amount of pointers is fixed by the amount of instance variables, but also, the pointer is always the same, one world (32 or 64 bits). Examples are any normal class like TestCase, Browser, True, Integer, etc.
  • Bytes: it means that the chunk of memory of an object is represented in a variable sequence of individual bytes.  Examples: ByteArray, ByteString, ByteSymbol, LargePositiveInteger, LargeNegativeInteger, etc.
  • Words: it is similar to “Bytes”, in the way that it is variable, but it is represented by a sequence of words instead. Notice that “Normal” also encodes the pointers in words, but in that case, the amount of those words is fixed and second they represent pointers. In this case, the amount of words is variable and they do not represent pointers to objects. Examples are Bitmap, WideString, WideSymbol, WordArray, FloatArray, etc.
  • Weak: when an object has weak references it means that its pointers to other objects don’t count for the Garbage Collector. So the GC removes and object when nobody else non-weak point to it. Weak format can be applied to both, variable and fixed formats. For example, WeakFinalizerItem has a normal format, but weak. On the contrary, WeakArray has a variable format and weak.
  • Variable: this is like “Normal” but where the pointers are not fixed, but instead variable. It can also be seen as “Words” but there each word does represent a pointer. Examples: BlockClosure, MethodDictionary, etc.
  • CompiledMethod: Chan! Chan! Chan! Yes, CompiledMethod class has its own format. Do you understand already why I wanted to talk about this before CompiledMethods?  But we will let the explanation to the end of the post…

Now…if you want to check by yourself, check the method Behavior >> #typeOfClass, it answers a symbol uniquely describing the format of the receiver class:

Behavior >> typeOfClass
"Answer a symbol uniquely describing the type of the receiver"
self instSpec = CompiledMethod instSpec ifTrue:[^#compiledMethod]. "Very special!"
self isBytes ifTrue:[^#bytes].
(self isWords and:[self isPointers not]) ifTrue:[^#words].
self isWeak ifTrue:[^#weak].
self isVariable ifTrue:[^#variable].
^#normal.

So you can do for example:

TestCase typeOfClass -> #normal
ByteArray typeOfClass -> #bytes
Bitmap typeOfClass -> #words
WeakArray typeOfClass -> #weak
BlockClosure typeOfClass -> #variable

Or you can inspect all classes of a certain type:

(Smalltalk allClasses select: [:each | each typeOfClass = #weak ]) inspect

Now, if you take a look to the method #typeOfClass we can see that it ask to itself whether it is bytes, or bits, or pointers, etc…In addition, notice the word “uniquely” in the comment of the method #typeOfClass. This means that the same class can be several “things” at the same time. For example:

Bitmap isVariable -> true
Bitmap isWords -> true
Bitmap isPointers -> false

BlockClosure isVariable -> true
BlockClosure isWords -> true
BlockClosure isPointers -> true

That example shows that all those classes that are “Words” or “Bytes” are also “variable”. Ahhh and btw…those variable classes supports Behavior >> #new: sizeOfVariables. Most classes in the Collection‘s hierarchy  are variable.

Prepare the image

In my post about compiling the VM I told you to use a PharoCore image since it was the “recommended” way. However, in the second post about building the VM, I provided you with a PharoDev 1.2.1 image ready to load Cog and its VMMaker branch.  So, even if you are not going to compile the VM, I recommend you to load Cog and VMMaker so that you could follow some of my comments. In addition, since we are not going to build the VM for a couple of posts, but instead understanding it, you can save this image and you will be able to use it in the next posts. Just thake the image and evaluate:

Deprecation raiseWarning: false.
Gofer new
squeaksource: 'MetacelloRepository';
package: 'ConfigurationOfCog';
load.
((Smalltalk at: #ConfigurationOfCog) project version: '2.0') load.

Class format encoding in classes and instances

If you see all those methods like #isBytes, #isVariable, #isPointers, etc (all those methods in the category ‘testing’ in Behavior class) you will notice that they all send #instSpec (instance specification I guess) at the end. And this method looks like this:

Behavior >> instSpec
^ (format bitShift: -7) bitAnd: 16rF

And a couple of examples:

TestCase instSpec -> 1
ByteArray instSpec -> 8
CompiledMethod instSpec -> 12

“format” is the instVar of Behavior, and as it says its getter method “Answer an Integer that encodes the kinds and numbers of variables of  instances of the receiver.”. So the number just alone is not really useful, but taking some bits from it yes, like #instSpec
, #instSize, #indexIfCompact, etc. So…the class encodes this information in an integer which is the “format” instVar.

But what happens to their instances?  Imagine that the VM for different tasks needs to how the format of a particular object. Fetching its class every time may be expensive. So where is such information stored? To answer, we will take our image and browse the “core” of the VM. Let’s see the method ObjectMemory >> formatOf:

formatOf: oop
"       0      no fields
1      fixed fields only (all containing pointers)
2      indexable fields only (all containing pointers)
3      both fixed and indexable fields (all containing pointers)
4      both fixed and indexable weak fields (all containing pointers).
5      unused
6      indexable word fields only (no pointers)
7      indexable long (64-bit) fields (only in 64-bit images)
8-11      indexable byte fields only (no pointers) (low 2 bits are low 2 bits of size)
12-15     compiled methods:
# of literal oops specified in method header,
followed by indexable bytes (same interpretation of low 2 bits as above)
"
<inline: true>
^((self baseHeader: oop) >> 8 ) bitAnd: 16rF

As you can see, there are 16 possible formats, encoded from 0 to 15 in 4 bits of the Object Header. The line “^((self baseHeader: oop) >> 8 ) bitAnd: 16rF” is the one that takes those 4 bits from the Object Header of the OOP (object pointer) received by parameter.

If you now browse the class comment of ObjectMemory, you will read it says that there are 4 bits for the object format. As you can guess, that number that represents the format is what we get in the image side with the method #instSpec. Notice that at the beginning of the post described all the different types of format and they were 6, but here we have 16 possibilities.  Ok, some are for optimizations (for example the number zero means that the object has no instVar, hence the GC can stop there while doing the mark and trace instead of trying to follow non-existent pointers), some are not used (like the number 5), some are only for 64 bits (number 7), the format for “bytes” uses 4 numbers, and CompiledMethod also uses 4 numbers.

Don’t get confused:  In the image side, we have an instVar which is called “format” in Behavior that keeps an integer with both, what WE call format plus the amount of variables. What we call format, is the method #instSpec in the image (which in fact gets the format from the “format” instVar). Finally, the VM agree with us, the method is #formatOf:  and it refers to what we call format. All in all, the instVar “format” of Behavior is misleading. Don’t get confused.

Finally, if you are curious you can check senders of #formatOf: and you will see all the places where the VM needs to know the format of an object.

Creating classes with a special format

We saw all the details of the class formats but we didn’t see how to create a class with a special one. In the previous post, I told you the way to create a subclass in Smalltalk was, of course, by sending a message. In this case, a message to the desired superclass. The method was Class >> #subclass:instanceVariableNames:classVariableNames:poolDictionaries:category: .  Now, if you check in the category of that method, that is, ‘subclass creation’ you will see much more methods like:

  • #variableSubclass: t instanceVariableNames: f classVariableNames: d poolDictionaries: s category: cat
  • #variableByteSubclass: t instanceVariableNames: f classVariableNames: d poolDictionaries: s category: cat
  • #variableWordSubclass: t instanceVariableNames: f  classVariableNames: d poolDictionaries: s category: cat
  • #weakSubclass: t instanceVariableNames: f  classVariableNames: d poolDictionaries: s category: cat

So…you image what each of those methods do, don’t you? If we want to confirm our suspicion, take a look to the definition of the classes. For example, we saw that Bitmap was “words” and ByteArray was “bytes”, hence:

ArrayedCollection variableWordSubclass: #Bitmap
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'Graphics-Primitives'

And:

ArrayedCollection variableByteSubclass: #ByteArray
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'Collections-Arrayed'

Do you notice the difference?  🙂    It is important to note also that there must be some validation. For example, if I define a class as variable with bytes, I shouldn’t be able to declare instance variables to that class, because I cannot mix both (only CompiledMethod do that!!!). So for example, if you try to do:

TestCase variableByteSubclass: #MarianoArray
instanceVariableNames: ' size '
classVariableNames: ''
poolDictionaries: ''
category: 'Collections-Arrayed'

You will get an error that says ‘cannot make a byte subclass of a class with named fields’. These validation are done by ClassBuilder.

CompiledMethod format

All this post was just to explain you the following 😉  As I said, CompiledMethod has a very special class format, and we can read it in his own class comment “My instances are methods suitable for interpretation by the virtual machine.  This is the only class in the system whose instances intermix both indexable pointer fields and indexable integer fields.”  This means that CompiledMethod was created with the message #variableByteSubclass:instanceVariableNames:classVariableNames:poolDictionaries:category:    and in addition:

CompiledMethod isBytes -> true
CompiledMethod isWords -> false  "lying!! he also includes words for pointers "
CompiledMethod isPointers -> false  "lying!! he also includes words for pointers"

So…the system thinks CompiledMethod is just a “Bytes” but it is not, it is a mix between bytes and pointers (words). The pointers are used to point to the literals and this part of the CompiledMethod is known as the “Literal Frame”. In fact, you will notice that the literals usually include a few type of objects: Symbols (for selectors), Association (for classes and globals), SmallInteger, ByteString for string constants, etc. The “bytes” part is the part used to encode the bytecodes (so it means we have only 255 possible bytecodes???  stay tuned…) . Example:

MyClass >> testSomething
TestCase new.
self name.
Transcript show: 'The answer is:', 42.

If you now inspect the literals, you can see something like this:

(MyClass >>#testSomething) literals ---->>>{(#TestCase->TestCase). #name. #show:. (#Transcript->Transcript). #,. 'The answer is:'. 42. #testSomething. (#MyClass->MyClass)}

So…those are regular objects: (#TestCase->TestCase)  is an Association, #name a Symbol, ‘I am hungry’ a Bytestring, 42 a SmallInteger, etc. Think this:  if you explore any of those objects and check for the pointers to them, will you see the CompiledMethod of #testSomething as one of the pointers to them??? we will see the answer next post, but basically it depends whether the tool takes into consideration or not this special magic of CompiledMethod.

Mmmm now I wonder which are the possible classes for literals? …if my Smalltalk doesn’t fail me:

(CompiledMethod allInstances
inject: OrderedCollection new
into: [:allTypesOfLiterals :aCompiledMethod | allTypesOfLiterals addAll: ((aCompiledMethod literals collect: [:aLiteral | aLiteral class]) asSet ); yourself  ]) asSet.

Prints: ” a Set(Float Association ByteArray WideString LargeNegativeInteger AdditionalMethodState Character ByteSymbol Fraction ByteString SmallInteger Array ScaledDecimal LargePositiveInteger)”

If the format is “Bytes” and there is supposed to be no pointers, how it is possible that we can ask for an object (a literal for example)?  Ok…if you see CompiledMethod >> objectAt:   it delegates to a primitive. But since now you know how to download VMMaker and go to StackInterpreter class >> initializePrimitiveTable  and see that the primitive method is in fact called #primitiveObjectAt and you can see the code of what it does (hint: CompiledMethod has a header which contains the amount of literals among other stuff).

To conclude, let’s say that CompiledMethod format is “Bytes” but in fact it is the only class in the system that mixes pointers (for the literals) with bytes (for the bytecodes). Because of this, and another couple of reasons, CompiledMethod is aunique  quite special class.

Finally, I let you homework 😉 If we inspect/explore a ByteArray, we get something like this:

However, if we explore a CompiledMethod we get an explorer that show us the literals and the bytecodes in a nice way. Like this one:

How do you think the Explorer can do such thing?  and the Inspector ?

See you