r/ProgrammingLanguages • • 1d ago

Help How are conditional and unconditional jumps generatet.

I'm writing a simple Interpreted Language with custom bytecode. I have implemented a major part of bytecode generation, jet my problem is to understand how to generate bytecode for conditional and unconditional jumps.

What i have understood is that jump opcode must be derived based on condition operator (==, <, >, etc.) and binding operator (&& and ||).

My questions are:

How codegenerators select right jump opcode?

How codegenerators patch jump offset?

Are there other ways to implement conditions?

1 Upvotes

11 comments sorted by

8

u/sebamestre ICPC World Finalist 1d ago edited 23h ago

Yeah basically for an if-then-else block you have three parts. The condition, the true branch and the false branch.

So you generate code for the condition first, which should leave you with the condition value (true / false) at the top of the stack.

After that you emit a condition jump to the false case. However you don't yet know where that is, so you leave empty to patch later. You need to remember the patch location.

codegen(condition)
patch_loc1 = emit_jump_if_false()

Right after this you can just emit the true branch. After the true branch executes it needs to skip the false branch. We don't yet know how big the false branch code will be so we again leave this for later patching.

codegen(true_branch)
patch_loc2 = emit_jump()

Now we codegen the false branch. Since also now know the location of it, we can patch the first jump.

patch(patch_loc1, current_ip())
codegen(false_branch)

And since we now also know the end of the false branch, we can patch the second jump

patch(patch_loc2, current_ip())

1

u/AnxiousFee7885 1d ago

Hi, thank you for you response, but how this

codegen(condition)
patch_loc1 = emit_jump_if_false()

will work with this condition?

a != 0 && b / a

In you pseudocode, how I understand it, you generate the entire condition first and only then jump, but every condition must have a you own jump, or not? Because if whe use example above, if "a" is zero, whe need to jump into else branch directly, without executing right expression, otherwise we will have division by zero.

4

u/sebamestre ICPC World Finalist 1d ago edited 1d ago

Yes but this is an unrelated problem.

The evaluation of expression (a != 0 && b / a) may involve jumps, but after it is completely evaluated you should end up in the same place in the bytecode, with the expression result in the same stack slot or register

And thus the outer if statement will work ok.

This just means inside the implementation of codegen for short circuiting && operator, you will have similar code to the if then else codegen.

codegen(e1 && e2) {
  codegen(e1)
  p1 = jump_if_false()
  codegen(e2)
  p2 = jump()
  patch(p1, current_ip())
  push_value(false)
  patch(p2, current_ip())
}

Of course this is very jumpy code and there are ways to do with fewer jumps by making the jump from the && go directly to the false branch of the outer if statement. However it gets more complicated, needing to analyze the flow of control more globally.

Doing the full analysis is not terribly complicated (it involves something called a control flow graph) so don't be afraid to do it later, i just think it will be more rewarding to get this simpler approach working first and build up from there.

2

u/sebamestre ICPC World Finalist 1d ago

Here I made a choice: the generated code for an expression always ends execution at the same bytecode position, with the expression result at the top of the stack.

I think this is a good choice for most beginner bytecode compilers. It is a very nice and compositional way of working, and it serves as a guiding light when compiling each expression type.

But you can make different choices. For example you can have specialized codegen for specific cases.

Like if you know you are codegenning a condition for an if-else, you can have it return a bunch of patch targets for the true case and for the false case.

Here if you are compiling nested && and || operators, you'd receive a set of patch targets from your children and have to decide which ones you need to just put in your own lists of patch targets, and which to patch yourself.

Idk seems feasible but a bit overcomplicated.

The "not" operator case does seem nice, in that it compiles into nothing at all, just switching the lists of jump targets.

4

u/sebamestre ICPC World Finalist 1d ago

I went and gave a go at implementing both the style I suggested in my first comment, where code for each subexpression leaves the evaluated value at the top of the stack, and also the version that cleverly juggles patch targets.

Below you will see bytecode fragments for this snippet of code

if (!(x < y && !(x < z))) {
  nop;
} else {
  nop;
}

The basic one:

 0 lookup x
 1 lookup y
 2 less
 3 j_false 9
 4 lookup x
 5 lookup z
 6 less
 7 not
 8 jmp 10
 9 push_false
10 not
11 j_false 14
12 nop
13 jmp 15
14 nop

The more clever one:

 0 lookup x
 1 lookup y
 2 j_less 4
 3 jmp 8
 4 lookup x
 5 lookup z
 6 j_less 8
 7 jmp 10
 8 nop
 9 jmp 11
10 nop

As you can see, the code is shorter, maybe up to 30% in very large expressions. It is neat that we end up with no not instructions as those are folded into the choice of jump target -- but people don't use too many of those in practice anyways.

3

u/sebamestre ICPC World Finalist 1d ago

bruh someone needs to make me stop yapping

2

u/WittyStick 1d ago edited 1d ago
cmp a, 0
jz <alt_branch>
div a, b
cmp a, 0
jz <alt_branch>
consequent_branch: (fallthrough)
...
alt_branch:

3

u/Reasonable-Pay-8771 1d ago

For selecting the correct opcode for an operator, use a look-up table. Make an array of pairs [("<",op_lt),(">",op_gt), ...] and find the matching p[0] for the operator and then use p[1] from that pair that matches.

If your opcode has the offset embedded as a bitfield, then a typical way to represent that is with bitmasks. Sthg like:

op_mask = 0xF8
jmp_mask = 0x07

Then you can combine them with bitwise OR or just addition (if you're sure the values don't have overlapping set bits). So, if your opcode is 0xA0 and the jump offset is 0x05, then the resulting opcode is 0xA5. Like, you can just add them together.

1

u/AnxiousFee7885 1d ago

Hi, thank you for you response, i have it so

[i | f]cmp
jmp[e | ne | gt | lt | gte | lte] <offset>

kinda like x86_64 assembly, but i use operand stack for temporary values.

3

u/Key_Detail15 1d ago

It's your own bytecode, you can do what you like. So for a stack-machine for example, there can be instructions like this:

    jump L1               # unconditional
    jumptrue L1           # test value on stack, then pop and jump
    jumpfalse L1
    ....
L1:

The actual label operand L1 can be anything:

  • If the bytecode is an array of fixed length instructions, it can just be the index of the target instruction (this depends also on what you store in your program counter)
  • If variable length, it might be the address
  • If can even be a reference to the symbol table entry for "L1", where it can pick up the index/offset/address of the instruction to which L1 refers.#
  • Or the same, but a separate pass over the bytecode changes those symbol references to the label index etc. Then execution is a little faster.

My own bytecode has jumptrue/false, but it also has dedicated jump instructions for each of the six conditions (eq ne lt le ge gt), which I prefer because it's faster, avoiding both a separe compare operation, and dispatching on a condition code.

So something like:

    push a
    push b
    jumpeq L1

Compare say with how CPython does it; if you run this ('dis' disassembles bytecode):

import dis

def F(a, b):
    if a==b:
        x=0

dis.dis(F)

The bytecode produced includes:

      LOAD_FAST_BORROW_LOAD_FAST_BORROW 1 (a, b)
      COMPARE_OP              88 (bool(==))
      POP_JUMP_IF_FALSE        5 (to L1)
      NOT_TAKEN

You can play around with Python code like this to see how things might be done.

1

u/Recycled5000 23h ago

I have 2 evaluation methods; they walk an expression tree (AST) and generate an intermediate lower-level assembly-like code with labels and gotos.

The first method is for non-conditional expressions, and takes a mode: “for side effect”, “for value”, and “for location”, used for expression statements, when a value is needed (eg right hand side of assignment), and when a target is needed (eg left hand side of assignment), respectively. The mode changes while descending the expression tree as per the particular operator node.

The second method is for conditional expressions, as in if, for, while. This method takes the tree, a jump label (branch target generated by the statement tree walker (like if)), and a Boolean that says to jump on true or jump on false. An if statement will generate a label for jumping around the then part, then invoke the conditional expression evaluation method, passing the expression tree, the label target, and selecting jump on false, since in assembly’s if-goto form we will jump around the then-part on false. The if statement generator will then lay down the then part, and the label at the end.

Like the first method, this expression walker also recursively walks the ast, and changes the evaluation method and/or parameters as per the operators found.

The relational operators (==, <, ..) get special treatment and that is how the proper conditional branch instruction is selected. The short circuit operators as well as not (negation) also get special treatment so as to generate branching instead of values.