Plain Assembly example – IF

The list of instructions will need to be extended With low level stuff as I mature the VM and implement it, but lets start writing some code and assemble it into actual instruction. I need to do this for every instruction and Assembly trick we use – lets start with IF..ElseIf..Else..End!

Ifeg, ifneq, ifgt, ifls, ifgte and iflse are all instructions that that use 1 x 16 bit for the op-code , and 2 x 16 bit register values for values that needs to be compared. It will in addition need 1×16 for an goto false. If itself is NOT an instruction in this design as we use the Assembler to convert this into an Assign combined With one of the other instructions.

ElseElseIf and End are Assembler abstractions.

If A = 1
            NOP
ElseIf A=2
            NOP
Else
            NOP
End

The small example above implement a classic If..Elsif..Else..End as we know it from 3. generation Languages. I use NOP since it is a single 16 bit register op-code- easy to count. Let us look at the 16 bit instruction array:

1 IF A = 1 < ifeq op code>
2 < A register index>
3 < 1 register index
4 < next instruction index is 8>
5    NOP < nop opcode>
6 < goto opcode>
7 < goto instruction is 16>
8 Elsif A=2 < ifeq op code>
9 < A register index>
10 < 2 register index>
11 < next instruction if false is 15>
12    NOP < nop opcode>
13 < goto opcode>
14 < goto instruction is 16>
15 Else < nop opcode>
16 End

This produced a 15 x 16 binary code – 12 of these are code generated from our if statements. One consequence is that I needed to re-introduce the goto instruction.

My main concern with the example above is that I start removing myself too much from an instruction by instruction assembly. This creates a challenge as I want to disassembly the previous code. I would in reality need something like this :

Start IFEQ A,1, next elseif1 4
NOP 1
Goto end 2
Elseif1 Ifeq A,2, next else1 4
Nop 1
Goto end 2
Else1 Nop 1
End

I have done object oriented VM’s earlier – the IF on that was an array with sub-trees for expressions and sub-code. The entire if..elseif..else was a single instruction. This VM is different and closer to machine code. It don’t give the same effect – that said it was no way I could execute this on 15×16 bit using the OO one. Also the OO needs dynamic memory so it is not an option to use that design here.

The conclusion (for now) is that I extend my assembly to include “Next” on IFEQ etc and also add the GOTO and associated Label. The drawback is that we are getting to close to actual ARM assembly for my taste. I will continue on other examples and see if I get a better idea/syntax Down the line.

Leave a Reply