I'm a little confused as to how the PVM gets the cpu to carry out the bytecode instructions. I had read somewhere on StackOverflow that it doesn't convert byte-code to machine code, (alas, I can't find the thread now).
Does it already have tons of pre-compiled machine instructions hard-coded that it runs/chooses one of those depending on the byte code?
Thank you.
An example of bytecode The CLASS file is then read and processed by a Java virtual machine (JVM) running on a target system. The JVM, which is part of the Java Runtime Environment, interprets the bytecode and converts it to machine language specific to the intended platform.
CPython's VM is stack-based. It means that it executes instructions using the stack to store and retrieve data. The LOAD_FAST instruction pushes a local variable onto the stack. LOAD_CONST pushes a constant.
Instead of translating source code to machine code like C++, Python code it translated to bytecode. This bytecode is a low-level set of instructions that can be executed by an interpreter.
The default implementation of the Python programming language is CPython which is written in the C programming language. CPython compiles the python source code into the bytecode, and this bytecode is then executed by the CPython virtual machine.
It's a lot higher-level than machine language. There's a giant switch
statement that looks at each opcode and decides what to do based on the opcode. Here are some snippets:
switch (opcode) {
...
TARGET(LOAD_CONST) {
PyObject *value = GETITEM(consts, oparg);
Py_INCREF(value);
PUSH(value);
FAST_DISPATCH();
}
...
TARGET(UNARY_NEGATIVE) {
PyObject *value = TOP();
PyObject *res = PyNumber_Negative(value);
Py_DECREF(value);
SET_TOP(res);
if (res == NULL)
goto error;
DISPATCH();
}
...
TARGET(BINARY_MULTIPLY) {
PyObject *right = POP();
PyObject *left = TOP();
PyObject *res = PyNumber_Multiply(left, right);
Py_DECREF(left);
Py_DECREF(right);
SET_TOP(res);
if (res == NULL)
goto error;
DISPATCH();
}
The TARGET
and DISPATCH
stuff is part of an optimization that doesn't quite go through the regular switch
mechanics. Functions like PyNumber_Negative
and PyNumber_Multiply
are part of the Python C API, and they dispatch operations like negation and multiplication.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With