Skip to content

Commit 4629567

Browse files
authored
GH-142305: JIT: Deduplicating GOT symbols in the trace (#142316)
1 parent 785268f commit 4629567

File tree

4 files changed

+153
-50
lines changed

4 files changed

+153
-50
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Decrease the size of the generated stencils and the runtime JIT code. Patch by Diego Russo.

Python/jit.c

Lines changed: 54 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -134,18 +134,20 @@ mark_executable(unsigned char *memory, size_t size)
134134

135135
// JIT compiler stuff: /////////////////////////////////////////////////////////
136136

137-
#define SYMBOL_MASK_WORDS 4
137+
#define GOT_SLOT_SIZE sizeof(uintptr_t)
138+
#define SYMBOL_MASK_WORDS 8
138139

139140
typedef uint32_t symbol_mask[SYMBOL_MASK_WORDS];
140141

141142
typedef struct {
142143
unsigned char *mem;
143144
symbol_mask mask;
144145
size_t size;
145-
} trampoline_state;
146+
} symbol_state;
146147

147148
typedef struct {
148-
trampoline_state trampolines;
149+
symbol_state trampolines;
150+
symbol_state got_symbols;
149151
uintptr_t instruction_starts[UOP_MAX_TRACE_LENGTH];
150152
} jit_state;
151153

@@ -210,6 +212,33 @@ set_bits(uint32_t *loc, uint8_t loc_start, uint64_t value, uint8_t value_start,
210212
// - x86_64-unknown-linux-gnu:
211213
// - https://github.com/llvm/llvm-project/blob/main/lld/ELF/Arch/X86_64.cpp
212214

215+
216+
// Get the symbol slot memory location for a given symbol ordinal.
217+
static unsigned char *
218+
get_symbol_slot(int ordinal, symbol_state *state, int size)
219+
{
220+
const uint32_t symbol_mask = 1U << (ordinal % 32);
221+
const uint32_t state_mask = state->mask[ordinal / 32];
222+
assert(symbol_mask & state_mask);
223+
224+
// Count the number of set bits in the symbol mask lower than ordinal
225+
size_t index = _Py_popcount32(state_mask & (symbol_mask - 1));
226+
for (int i = 0; i < ordinal / 32; i++) {
227+
index += _Py_popcount32(state->mask[i]);
228+
}
229+
230+
unsigned char *slot = state->mem + index * size;
231+
assert((size_t)(index + 1) * size <= state->size);
232+
return slot;
233+
}
234+
235+
// Return the address of the GOT slot for the requested symbol ordinal.
236+
static uintptr_t
237+
got_symbol_address(int ordinal, jit_state *state)
238+
{
239+
return (uintptr_t)get_symbol_slot(ordinal, &state->got_symbols, GOT_SLOT_SIZE);
240+
}
241+
213242
// Many of these patches are "relaxing", meaning that they can rewrite the
214243
// code they're patching to be more efficient (like turning a 64-bit memory
215244
// load into a 32-bit immediate load). These patches have an "x" in their name.
@@ -452,6 +481,7 @@ patch_x86_64_32rx(unsigned char *location, uint64_t value)
452481
patch_32r(location, value);
453482
}
454483

484+
void patch_got_symbol(jit_state *state, int ordinal);
455485
void patch_aarch64_trampoline(unsigned char *location, int ordinal, jit_state *state);
456486
void patch_x86_64_trampoline(unsigned char *location, int ordinal, jit_state *state);
457487

@@ -470,23 +500,13 @@ void patch_x86_64_trampoline(unsigned char *location, int ordinal, jit_state *st
470500
#define DATA_ALIGN 1
471501
#endif
472502

473-
// Get the trampoline memory location for a given symbol ordinal.
474-
static unsigned char *
475-
get_trampoline_slot(int ordinal, jit_state *state)
503+
// Populate the GOT entry for the given symbol ordinal with its resolved address.
504+
void
505+
patch_got_symbol(jit_state *state, int ordinal)
476506
{
477-
const uint32_t symbol_mask = 1 << (ordinal % 32);
478-
const uint32_t trampoline_mask = state->trampolines.mask[ordinal / 32];
479-
assert(symbol_mask & trampoline_mask);
480-
481-
// Count the number of set bits in the trampoline mask lower than ordinal
482-
int index = _Py_popcount32(trampoline_mask & (symbol_mask - 1));
483-
for (int i = 0; i < ordinal / 32; i++) {
484-
index += _Py_popcount32(state->trampolines.mask[i]);
485-
}
486-
487-
unsigned char *trampoline = state->trampolines.mem + index * TRAMPOLINE_SIZE;
488-
assert((size_t)(index + 1) * TRAMPOLINE_SIZE <= state->trampolines.size);
489-
return trampoline;
507+
uint64_t value = (uintptr_t)symbols_map[ordinal];
508+
unsigned char *location = (unsigned char *)get_symbol_slot(ordinal, &state->got_symbols, GOT_SLOT_SIZE);
509+
patch_64(location, value);
490510
}
491511

492512
// Generate and patch AArch64 trampolines. The symbols to jump to are stored
@@ -506,8 +526,7 @@ patch_aarch64_trampoline(unsigned char *location, int ordinal, jit_state *state)
506526
}
507527

508528
// Out of range - need a trampoline
509-
uint32_t *p = (uint32_t *)get_trampoline_slot(ordinal, state);
510-
529+
uint32_t *p = (uint32_t *)get_symbol_slot(ordinal, &state->trampolines, TRAMPOLINE_SIZE);
511530

512531
/* Generate the trampoline
513532
0: 58000048 ldr x8, 8
@@ -537,7 +556,7 @@ patch_x86_64_trampoline(unsigned char *location, int ordinal, jit_state *state)
537556
}
538557

539558
// Out of range - need a trampoline
540-
unsigned char *trampoline = get_trampoline_slot(ordinal, state);
559+
unsigned char *trampoline = get_symbol_slot(ordinal, &state->trampolines, TRAMPOLINE_SIZE);
541560

542561
/* Generate the trampoline (14 bytes, padded to 16):
543562
0: ff 25 00 00 00 00 jmp *(%rip)
@@ -579,21 +598,26 @@ _PyJIT_Compile(_PyExecutorObject *executor, const _PyUOpInstruction trace[], siz
579598
code_size += group->code_size;
580599
data_size += group->data_size;
581600
combine_symbol_mask(group->trampoline_mask, state.trampolines.mask);
601+
combine_symbol_mask(group->got_mask, state.got_symbols.mask);
582602
}
583603
group = &stencil_groups[_FATAL_ERROR];
584604
code_size += group->code_size;
585605
data_size += group->data_size;
586606
combine_symbol_mask(group->trampoline_mask, state.trampolines.mask);
607+
combine_symbol_mask(group->got_mask, state.got_symbols.mask);
587608
// Calculate the size of the trampolines required by the whole trace
588609
for (size_t i = 0; i < Py_ARRAY_LENGTH(state.trampolines.mask); i++) {
589610
state.trampolines.size += _Py_popcount32(state.trampolines.mask[i]) * TRAMPOLINE_SIZE;
590611
}
612+
for (size_t i = 0; i < Py_ARRAY_LENGTH(state.got_symbols.mask); i++) {
613+
state.got_symbols.size += _Py_popcount32(state.got_symbols.mask[i]) * GOT_SLOT_SIZE;
614+
}
591615
// Round up to the nearest page:
592616
size_t page_size = get_page_size();
593617
assert((page_size & (page_size - 1)) == 0);
594618
size_t code_padding = DATA_ALIGN - ((code_size + state.trampolines.size) & (DATA_ALIGN - 1));
595-
size_t padding = page_size - ((code_size + state.trampolines.size + code_padding + data_size) & (page_size - 1));
596-
size_t total_size = code_size + state.trampolines.size + code_padding + data_size + padding;
619+
size_t padding = page_size - ((code_size + state.trampolines.size + code_padding + data_size + state.got_symbols.size) & (page_size - 1));
620+
size_t total_size = code_size + state.trampolines.size + code_padding + data_size + state.got_symbols.size + padding;
597621
unsigned char *memory = jit_alloc(total_size);
598622
if (memory == NULL) {
599623
return -1;
@@ -603,6 +627,7 @@ _PyJIT_Compile(_PyExecutorObject *executor, const _PyUOpInstruction trace[], siz
603627
OPT_STAT_ADD(jit_code_size, code_size);
604628
OPT_STAT_ADD(jit_trampoline_size, state.trampolines.size);
605629
OPT_STAT_ADD(jit_data_size, data_size);
630+
OPT_STAT_ADD(jit_got_size, state.got_symbols.size);
606631
OPT_STAT_ADD(jit_padding_size, padding);
607632
OPT_HIST(total_size, trace_total_memory_hist);
608633
// Update the offsets of each instruction:
@@ -613,6 +638,7 @@ _PyJIT_Compile(_PyExecutorObject *executor, const _PyUOpInstruction trace[], siz
613638
unsigned char *code = memory;
614639
state.trampolines.mem = memory + code_size;
615640
unsigned char *data = memory + code_size + state.trampolines.size + code_padding;
641+
state.got_symbols.mem = data + data_size;
616642
assert(trace[0].opcode == _START_EXECUTOR || trace[0].opcode == _COLD_EXIT || trace[0].opcode == _COLD_DYNAMIC_EXIT);
617643
for (size_t i = 0; i < length; i++) {
618644
const _PyUOpInstruction *instruction = &trace[i];
@@ -654,19 +680,21 @@ compile_trampoline(void)
654680
code_size += group->code_size;
655681
data_size += group->data_size;
656682
combine_symbol_mask(group->trampoline_mask, state.trampolines.mask);
683+
combine_symbol_mask(group->got_mask, state.got_symbols.mask);
657684
// Round up to the nearest page:
658685
size_t page_size = get_page_size();
659686
assert((page_size & (page_size - 1)) == 0);
660687
size_t code_padding = DATA_ALIGN - ((code_size + state.trampolines.size) & (DATA_ALIGN - 1));
661-
size_t padding = page_size - ((code_size + state.trampolines.size + code_padding + data_size) & (page_size - 1));
662-
size_t total_size = code_size + state.trampolines.size + code_padding + data_size + padding;
688+
size_t padding = page_size - ((code_size + state.trampolines.size + code_padding + data_size + state.got_symbols.size) & (page_size - 1));
689+
size_t total_size = code_size + state.trampolines.size + code_padding + data_size + state.got_symbols.size + padding;
663690
unsigned char *memory = jit_alloc(total_size);
664691
if (memory == NULL) {
665692
return NULL;
666693
}
667694
unsigned char *code = memory;
668695
state.trampolines.mem = memory + code_size;
669696
unsigned char *data = memory + code_size + state.trampolines.size + code_padding;
697+
state.got_symbols.mem = data + data_size;
670698
// Compile the shim, which handles converting between the native
671699
// calling convention and the calling convention used by jitted code
672700
// (which may be different for efficiency reasons).

Tools/jit/_stencils.py

Lines changed: 97 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -100,8 +100,8 @@ class HoleValue(enum.Enum):
100100
HoleValue.CODE: "(uintptr_t)code",
101101
HoleValue.DATA: "(uintptr_t)data",
102102
HoleValue.EXECUTOR: "(uintptr_t)executor",
103+
HoleValue.GOT: "",
103104
# These should all have been turned into DATA values by process_relocations:
104-
# HoleValue.GOT: "",
105105
HoleValue.OPARG: "instruction->oparg",
106106
HoleValue.OPERAND0: "instruction->operand0",
107107
HoleValue.OPERAND0_HI: "(instruction->operand0 >> 32)",
@@ -115,6 +115,24 @@ class HoleValue(enum.Enum):
115115
HoleValue.ZERO: "",
116116
}
117117

118+
_AARCH64_GOT_RELOCATIONS = {
119+
"R_AARCH64_ADR_GOT_PAGE",
120+
"R_AARCH64_LD64_GOT_LO12_NC",
121+
"ARM64_RELOC_GOT_LOAD_PAGE21",
122+
"ARM64_RELOC_GOT_LOAD_PAGEOFF12",
123+
"IMAGE_REL_ARM64_PAGEBASE_REL21",
124+
"IMAGE_REL_ARM64_PAGEOFFSET_12L",
125+
"IMAGE_REL_ARM64_PAGEOFFSET_12A",
126+
}
127+
128+
_X86_GOT_RELOCATIONS = {
129+
"R_X86_64_GOTPCRELX",
130+
"R_X86_64_REX_GOTPCRELX",
131+
"X86_64_RELOC_GOT",
132+
"X86_64_RELOC_GOT_LOAD",
133+
"IMAGE_REL_AMD64_REL32",
134+
}
135+
118136

119137
@dataclasses.dataclass
120138
class Hole:
@@ -133,6 +151,8 @@ class Hole:
133151
# ...plus this addend:
134152
addend: int
135153
need_state: bool = False
154+
custom_location: str = ""
155+
custom_value: str = ""
136156
func: str = dataclasses.field(init=False)
137157
# Convenience method:
138158
replace = dataclasses.replace
@@ -170,16 +190,22 @@ def fold(self, other: typing.Self, body: bytearray) -> typing.Self | None:
170190

171191
def as_c(self, where: str) -> str:
172192
"""Dump this hole as a call to a patch_* function."""
173-
location = f"{where} + {self.offset:#x}"
174-
value = _HOLE_EXPRS[self.value]
175-
if self.symbol:
176-
if value:
177-
value += " + "
178-
value += f"(uintptr_t)&{self.symbol}"
179-
if _signed(self.addend) or not value:
180-
if value:
181-
value += " + "
182-
value += f"{_signed(self.addend):#x}"
193+
if self.custom_location:
194+
location = self.custom_location
195+
else:
196+
location = f"{where} + {self.offset:#x}"
197+
if self.custom_value:
198+
value = self.custom_value
199+
else:
200+
value = _HOLE_EXPRS[self.value]
201+
if self.symbol:
202+
if value:
203+
value += " + "
204+
value += f"(uintptr_t)&{self.symbol}"
205+
if _signed(self.addend) or not value:
206+
if value:
207+
value += " + "
208+
value += f"{_signed(self.addend):#x}"
183209
if self.need_state:
184210
return f"{self.func}({location}, {value}, state);"
185211
return f"{self.func}({location}, {value});"
@@ -219,8 +245,11 @@ class StencilGroup:
219245
symbols: dict[int | str, tuple[HoleValue, int]] = dataclasses.field(
220246
default_factory=dict, init=False
221247
)
222-
_got: dict[str, int] = dataclasses.field(default_factory=dict, init=False)
248+
_jit_symbol_table: dict[str, int] = dataclasses.field(
249+
default_factory=dict, init=False
250+
)
223251
_trampolines: set[int] = dataclasses.field(default_factory=set, init=False)
252+
_got_entries: set[int] = dataclasses.field(default_factory=set, init=False)
224253

225254
def convert_labels_to_relocations(self) -> None:
226255
for name, hole_plus in self.symbols.items():
@@ -270,13 +299,39 @@ def process_relocations(self, known_symbols: dict[str, int]) -> None:
270299
self._trampolines.add(ordinal)
271300
hole.addend = ordinal
272301
hole.symbol = None
302+
elif (
303+
hole.kind in _AARCH64_GOT_RELOCATIONS | _X86_GOT_RELOCATIONS
304+
and hole.symbol
305+
and "_JIT_" not in hole.symbol
306+
and hole.value is HoleValue.GOT
307+
):
308+
if hole.symbol in known_symbols:
309+
ordinal = known_symbols[hole.symbol]
310+
else:
311+
ordinal = len(known_symbols)
312+
known_symbols[hole.symbol] = ordinal
313+
self._got_entries.add(ordinal)
273314
self.data.pad(8)
274315
for stencil in [self.code, self.data]:
275316
for hole in stencil.holes:
276317
if hole.value is HoleValue.GOT:
277318
assert hole.symbol is not None
278-
hole.value = HoleValue.DATA
279-
hole.addend += self._global_offset_table_lookup(hole.symbol)
319+
if "_JIT_" in hole.symbol:
320+
# Relocations for local symbols
321+
hole.value = HoleValue.DATA
322+
hole.addend += self._jit_symbol_table_lookup(hole.symbol)
323+
else:
324+
_ordinal = known_symbols[hole.symbol]
325+
_custom_value = f"got_symbol_address({_ordinal:#x}, state)"
326+
if hole.kind in _X86_GOT_RELOCATIONS:
327+
# When patching on x86, subtract the addend -4
328+
# that is used to compute the 32 bit RIP relative
329+
# displacement to the GOT entry
330+
_custom_value = (
331+
f"got_symbol_address({_ordinal:#x}, state) - 4"
332+
)
333+
hole.addend = _ordinal
334+
hole.custom_value = _custom_value
280335
hole.symbol = None
281336
elif hole.symbol in self.symbols:
282337
hole.value, addend = self.symbols[hole.symbol]
@@ -289,16 +344,19 @@ def process_relocations(self, known_symbols: dict[str, int]) -> None:
289344
raise ValueError(
290345
f"Add PyAPI_FUNC(...) or PyAPI_DATA(...) to declaration of {hole.symbol}!"
291346
)
347+
self._emit_jit_symbol_table()
292348
self._emit_global_offset_table()
293349
self.code.holes.sort(key=lambda hole: hole.offset)
294350
self.data.holes.sort(key=lambda hole: hole.offset)
295351

296-
def _global_offset_table_lookup(self, symbol: str) -> int:
297-
return len(self.data.body) + self._got.setdefault(symbol, 8 * len(self._got))
352+
def _jit_symbol_table_lookup(self, symbol: str) -> int:
353+
return len(self.data.body) + self._jit_symbol_table.setdefault(
354+
symbol, 8 * len(self._jit_symbol_table)
355+
)
298356

299-
def _emit_global_offset_table(self) -> None:
357+
def _emit_jit_symbol_table(self) -> None:
300358
got = len(self.data.body)
301-
for s, offset in self._got.items():
359+
for s, offset in self._jit_symbol_table.items():
302360
if s in self.symbols:
303361
value, addend = self.symbols[s]
304362
symbol = None
@@ -322,20 +380,35 @@ def _emit_global_offset_table(self) -> None:
322380
)
323381
self.data.body.extend([0] * 8)
324382

325-
def _get_trampoline_mask(self) -> str:
383+
def _emit_global_offset_table(self) -> None:
384+
for hole in self.code.holes:
385+
if hole.value is HoleValue.GOT:
386+
_got_hole = Hole(0, "R_X86_64_64", hole.value, None, hole.addend)
387+
_got_hole.func = "patch_got_symbol"
388+
_got_hole.custom_location = "state"
389+
if _got_hole not in self.data.holes:
390+
self.data.holes.append(_got_hole)
391+
392+
def _get_symbol_mask(self, ordinals: set[int]) -> str:
326393
bitmask: int = 0
327-
trampoline_mask: list[str] = []
328-
for ordinal in self._trampolines:
394+
symbol_mask: list[str] = []
395+
for ordinal in ordinals:
329396
bitmask |= 1 << ordinal
330397
while bitmask:
331398
word = bitmask & ((1 << 32) - 1)
332-
trampoline_mask.append(f"{word:#04x}")
399+
symbol_mask.append(f"{word:#04x}")
333400
bitmask >>= 32
334-
return "{" + (", ".join(trampoline_mask) or "0") + "}"
401+
return "{" + (", ".join(symbol_mask) or "0") + "}"
402+
403+
def _get_trampoline_mask(self) -> str:
404+
return self._get_symbol_mask(self._trampolines)
405+
406+
def _get_got_mask(self) -> str:
407+
return self._get_symbol_mask(self._got_entries)
335408

336409
def as_c(self, opname: str) -> str:
337410
"""Dump this hole as a StencilGroup initializer."""
338-
return f"{{emit_{opname}, {len(self.code.body)}, {len(self.data.body)}, {self._get_trampoline_mask()}}}"
411+
return f"{{emit_{opname}, {len(self.code.body)}, {len(self.data.body)}, {self._get_trampoline_mask()}, {self._get_got_mask()}}}"
339412

340413

341414
def symbol_to_value(symbol: str) -> tuple[HoleValue, str | None]:

Tools/jit/_writer.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ def _dump_footer(
2020
yield " size_t code_size;"
2121
yield " size_t data_size;"
2222
yield " symbol_mask trampoline_mask;"
23+
yield " symbol_mask got_mask;"
2324
yield "} StencilGroup;"
2425
yield ""
2526
yield f"static const StencilGroup trampoline = {groups['trampoline'].as_c('trampoline')};"

0 commit comments

Comments
 (0)