| 1 |
"""Utilities for writing StencilGroups out to a C header file.""" |
| 2 |
|
| 3 |
import typing |
| 4 |
|
| 5 |
import _stencils |
| 6 |
|
| 7 |
|
| 8 |
def _dump_footer(groups: dict[str, _stencils.StencilGroup]) -> typing.Iterator[str]: |
| 9 |
yield "typedef struct {" |
| 10 |
yield " void (*emit)(" |
| 11 |
yield " unsigned char *code, unsigned char *data, _PyExecutorObject *executor," |
| 12 |
yield " const _PyUOpInstruction *instruction, uintptr_t instruction_starts[]);" |
| 13 |
yield " size_t code_size;" |
| 14 |
yield " size_t data_size;" |
| 15 |
yield "} StencilGroup;" |
| 16 |
yield "" |
| 17 |
yield f"static const StencilGroup trampoline = {groups['trampoline'].as_c('trampoline')};" |
| 18 |
yield "" |
| 19 |
yield "static const StencilGroup stencil_groups[MAX_UOP_ID + 1] = {" |
| 20 |
for opname, group in sorted(groups.items()): |
| 21 |
if opname == "trampoline": |
| 22 |
continue |
| 23 |
yield f" [{opname}] = {group.as_c(opname)}," |
| 24 |
yield "};" |
| 25 |
|
| 26 |
|
| 27 |
def _dump_stencil(opname: str, group: _stencils.StencilGroup) -> typing.Iterator[str]: |
| 28 |
yield "void" |
| 29 |
yield f"emit_{opname}(" |
| 30 |
yield " unsigned char *code, unsigned char *data, _PyExecutorObject *executor," |
| 31 |
yield " const _PyUOpInstruction *instruction, uintptr_t instruction_starts[])" |
| 32 |
yield "{" |
| 33 |
for part, stencil in [("code", group.code), ("data", group.data)]: |
| 34 |
for line in stencil.disassembly: |
| 35 |
yield f" // {line}" |
| 36 |
if stencil.body: |
| 37 |
yield f" const unsigned char {part}_body[{len(stencil.body)}] = {{" |
| 38 |
for i in range(0, len(stencil.body), 8): |
| 39 |
row = " ".join(f"{byte:#04x}," for byte in stencil.body[i : i + 8]) |
| 40 |
yield f" {row}" |
| 41 |
yield " };" |
| 42 |
# Data is written first (so relaxations in the code work properly): |
| 43 |
for part, stencil in [("data", group.data), ("code", group.code)]: |
| 44 |
if stencil.body: |
| 45 |
yield f" memcpy({part}, {part}_body, sizeof({part}_body));" |
| 46 |
stencil.holes.sort(key=lambda hole: hole.offset) |
| 47 |
for hole in stencil.holes: |
| 48 |
yield f" {hole.as_c(part)}" |
| 49 |
yield "}" |
| 50 |
yield "" |
| 51 |
|
| 52 |
|
| 53 |
def dump(groups: dict[str, _stencils.StencilGroup]) -> typing.Iterator[str]: |
| 54 |
"""Yield a JIT compiler line-by-line as a C header file.""" |
| 55 |
for opname, group in sorted(groups.items()): |
| 56 |
yield from _dump_stencil(opname, group) |
| 57 |
yield from _dump_footer(groups) |