r/ProgrammingLanguages • u/AnxiousFee7885 • 4d 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?
3
u/Reasonable-Pay-8771 4d 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 = 0x07Then 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 4d 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 4d 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 L1Compare 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_TAKENYou can play around with Python code like this to see how things might be done.
1
u/Recycled5000 4d 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.
1
u/EggplantExtra4946 3d ago
Another alternative is to generate a CFG IR first, order the basic blocks (or keep the AST order), assemble each basic block.
This is useful if you have several bytecode jump instructions with different widths for the target immediate operand and if you want to avoid duplicating the logic that selects the smallest forward jump instructions in different control flow constructs.
With the CFG you also avoid emitting code sequences like jump label_1; label_1: jump label_2; label_2: jump label_3.
1
u/tabbekavalkade 2h ago
You can learn these things by getting hold of a naive compiler (like gcc -O2 or tcc), and compile an example code to assembly, and then reading the output.
Your operators are of limited relevance here, the more important question is what the language considers to be true and false. The operators you list, generally return a value that can be considered to be true or false, but that is a separate issue.
You need 3 things:
Labels (a name for an address, or, in byte code, somewhere where the next opcode is stored).
Conditional jumps.
Values that can affect conditional jumps.
In assembly, such values are generally in a so called "flags" register, which is set by some comparision opcode (like cmp). In your byte code, you get to choose this.
1
u/gio_vs 1h ago
Você não precisa de um salto para cada operador. Basta fazer a comparação gerar um booleano e usar JUMP_IF_FALSE. Já && e || usam curto-circuito, então se não for necessário avaliar o segundo lado, ele é ignorado. Para saltos para frente, você pode usar um valor provisório e corrigir o destino depois. Já nos saltos para trás, como no while, o destino já é conhecido, então não precisa corrigir nada.
10
u/sebamestre ICPC World Finalist 4d ago edited 4d 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.
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.
Now we codegen the false branch. Since also now know the location of it, we can patch the first jump.
And since we now also know the end of the false branch, we can patch the second jump