Skip to content

Commit b16523a

Browse files
committed
vm: Don't unconditionally allocate state on stack, do that only if needed.
This makes sure that only as much stack allocated as actually used, reducing stack usage for each Python function call.
1 parent ff8da0b commit b16523a

File tree

1 file changed

+7
-4
lines changed

1 file changed

+7
-4
lines changed

py/vm.c

+7-4
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
#include <stdio.h>
2929
#include <string.h>
3030
#include <assert.h>
31+
#include <alloca.h>
3132

3233
#include "mpconfig.h"
3334
#include "nlr.h"
@@ -117,21 +118,23 @@ mp_vm_return_kind_t mp_execute_bytecode(const byte *code, const mp_obj_t *args,
117118
ip += 4;
118119

119120
// allocate state for locals and stack
120-
mp_obj_t temp_state[VM_MAX_STATE_ON_STACK];
121-
mp_obj_t *state = &temp_state[0];
122121
#if DETECT_VM_STACK_OVERFLOW
123122
n_state += 1;
124123
#endif
124+
mp_obj_t *state;
125125
if (n_state > VM_MAX_STATE_ON_STACK) {
126126
state = m_new(mp_obj_t, n_state);
127+
} else {
128+
state = alloca(sizeof(mp_obj_t) * n_state);
127129
}
128130
mp_obj_t *sp = &state[0] - 1;
129131

130132
// allocate state for exceptions
131-
mp_exc_stack_t exc_state[VM_MAX_EXC_STATE_ON_STACK];
132-
mp_exc_stack_t *exc_stack = &exc_state[0];
133+
mp_exc_stack_t *exc_stack;
133134
if (n_exc_stack > VM_MAX_EXC_STATE_ON_STACK) {
134135
exc_stack = m_new(mp_exc_stack_t, n_exc_stack);
136+
} else {
137+
exc_stack = alloca(sizeof(mp_exc_stack_t) * n_exc_stack);
135138
}
136139
mp_exc_stack_t *exc_sp = &exc_stack[0] - 1;
137140

0 commit comments

Comments
 (0)