Debian Codegraph @

Tools/jit/_writer.py

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