diff --git a/.github/workflows/test_basic.yaml b/.github/workflows/test_basic.yaml index fdc4e758f..d736f6d2c 100644 --- a/.github/workflows/test_basic.yaml +++ b/.github/workflows/test_basic.yaml @@ -20,6 +20,7 @@ jobs: - slothy.targets.aarch64.apple_m1_icestorm_experimental - slothy.targets.aarch64.aarch64_big_experimental - slothy.targets.riscv.xuantie_c908 + - slothy.targets.x86_64.intel_atom steps: - uses: actions/checkout@v3 - uses: ./.github/actions/setup-ubuntu @@ -41,6 +42,7 @@ jobs: - slothy.targets.aarch64.apple_m1_icestorm_experimental - slothy.targets.aarch64.aarch64_big_experimental - slothy.targets.riscv.xuantie_c908 + - slothy.targets.x86_64.intel_atom steps: - uses: actions/checkout@v3 - uses: ./.github/actions/setup-ubuntu diff --git a/README.md b/README.md index ee315c165..f938825e2 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,7 @@ SLOTHY is generic in the target architecture and microarchitecture. This reposit - Armv8.1-M+Helium: Cortex-M55, Cortex-M85 - AArch64: Cortex-A55, and experimentally Cortex-A72, Cortex-X/Neoverse-V, Apple M1 (Firestorm, Icestorm) - RISC-V (RV{32,64}IMB): XuanTie C908 +- x86_64 (AT&T syntax): experimentally Intel Atom (Bonnell) SLOTHY is discussed in [Fast and Clean: Auditable high-performance assembly via constraint solving](https://eprint.iacr.org/2022/1303). diff --git a/common/OptimizationRunner.py b/common/OptimizationRunner.py index 9e5b3d48e..22e44b0b1 100644 --- a/common/OptimizationRunner.py +++ b/common/OptimizationRunner.py @@ -48,6 +48,9 @@ import slothy.targets.riscv.riscv as RISCV import slothy.targets.riscv.xuantie_c908 as Target_XuanTieC908 +import slothy.targets.x86_64.x86_64 as X86_64 +import slothy.targets.x86_64.intel_atom as Target_IntelAtom + target_label_dict = { Target_CortexA55: "a55", Target_CortexA72: "a72", @@ -59,6 +62,7 @@ Target_AppleM1_icestorm: "m1_icestorm", Target_AArch64Big: "aarch64_big", Target_XuanTieC908: "c908", + Target_IntelAtom: "atom", } arch_label_dict = { @@ -66,6 +70,7 @@ Arch_Armv81M: "armv8m", AArch64_Neon: "aarch64", RISCV: "riscv", + X86_64: "x86_64", } diff --git a/docs/source/faq.md b/docs/source/faq.md index 802c36559..a05bb6b1d 100644 --- a/docs/source/faq.md +++ b/docs/source/faq.md @@ -19,8 +19,8 @@ It is thus independent of and potentially combinable with superoptimizers operat ## Does SLOTHY support x86? -The core of SLOTHY is architecture- and microarchitecture-agnostic and can accommodate x86. As it stands, however, -there is no model of the x86 architecture. Feel free to build one! +Yes, partially. SLOTHY includes an x86_64 model (AT&T syntax) covering the instructions needed for Keccak, and a uArch model for +Intel Atom (Bonnell). Loop optimization on x86_64 is not yet safe, because flag writes are only partially modelled. ## Does SLOTHY support RISC-V? diff --git a/docs/source/general.md b/docs/source/general.md index 78c09ce66..d9e101125 100644 --- a/docs/source/general.md +++ b/docs/source/general.md @@ -10,6 +10,7 @@ SLOTHY is generic in the target architecture and microarchitecture. This reposit - Armv8.1-M+Helium: Cortex-M55, Cortex-M85 - AArch64: Cortex-A55, and experimentally Cortex-A72, Cortex-X/Neoverse-V, Apple M1 (Firestorm, Icestorm) - RISC-V (RV{32,64}IMB): XuanTie C908 +- x86_64 (AT&T syntax): experimentally Intel Atom (Bonnell) SLOTHY is discussed in [Fast and Clean: Auditable high-performance assembly via constraint solving](https://eprint.iacr.org/2022/1303). diff --git a/example.py b/example.py index afc09e07c..a40f11a13 100644 --- a/example.py +++ b/example.py @@ -41,6 +41,8 @@ import slothy.targets.riscv.xuantie_c908 as Target_C908 +import slothy.targets.x86_64.intel_atom as Target_IntelAtom + ########################################################################################## from examples.naive.aarch64.dilithium._example import ( @@ -105,6 +107,10 @@ example_instances as example_instances_riscv_keccak, ) +from examples.naive.x86_64.simple._example import ( + example_instances as example_instances_x86_64_simple, +) + def main(): examples = ( @@ -126,6 +132,7 @@ def main(): + example_instances_riscv_ntt_kyber + example_instances_riscv_kyber_basemul + example_instances_riscv_keccak + + example_instances_x86_64_simple ) all_example_names = [e.name for e in examples] @@ -163,6 +170,7 @@ def main(): Target_AppleM1_icestorm.__name__, Target_AArch64Big.__name__, Target_C908.__name__, + Target_IntelAtom.__name__, ], ) args = parser.parse_args() diff --git a/examples/naive/x86_64/simple/_example.py b/examples/naive/x86_64/simple/_example.py new file mode 100644 index 000000000..0e261556c --- /dev/null +++ b/examples/naive/x86_64/simple/_example.py @@ -0,0 +1,74 @@ +# +# Copyright (c) 2026 Maggie Simmons +# Copyright (c) 2026 Hayden Parsons +# SPDX-License-Identifier: MIT +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. +# + +import os + +from common.OptimizationRunner import OptimizationRunner +import slothy.targets.x86_64.x86_64 as Arch_X86_64 +import slothy.targets.x86_64.intel_atom as Target_IntelAtom + +SUBFOLDER = os.path.basename(os.path.dirname(__file__)) + "/" + + +class X86_64Simple(OptimizationRunner): + def __init__(self, var="", arch=Arch_X86_64, target=Target_IntelAtom, timeout=None): + name = "x86_64_simple" + super().__init__( + name, + name, + subfolder=SUBFOLDER, + arch=arch, + target=target, + timeout=timeout, + var=var, + ) + + def core(self, slothy): + slothy.config.variable_size = True + # Keep input registers (e.g. the rdi/rsi pointers) intact + slothy.config.inputs_are_outputs = True + + # Every non-branch instruction form; results end up in memory + slothy.optimize(start="start", end="end") + + # 8/16/32-bit register forms + slothy.config.outputs = ["al", "bx", "ecx"] + slothy.optimize(start="start_subregisters", end="end_subregisters") + slothy.config.outputs = [] + + # Symbolic registers and memory hints (selftest is skipped for symbolic code) + slothy.optimize(start="start_symbolic", end="end_symbolic") + + # Split xor-with-memory, then optimize with the opt-in memory constraint + slothy.fusion_region("start_fusion", "end_fusion", ssa=False) + Target_IntelAtom.memory_offset_constraint = True + try: + slothy.optimize(start="start_fusion", end="end_fusion") + finally: + Target_IntelAtom.memory_offset_constraint = False + + +example_instances = [ + X86_64Simple(), +] diff --git a/examples/naive/x86_64/simple/x86_64_simple.s b/examples/naive/x86_64/simple/x86_64_simple.s new file mode 100644 index 000000000..7229f02ec --- /dev/null +++ b/examples/naive/x86_64/simple/x86_64_simple.s @@ -0,0 +1,81 @@ +// x86_64 example for the Intel Atom (Bonnell) model, AT&T syntax. +// +// Four regions, optimized separately (see _example.py): +// start / end every non-branch instruction form (selftest runs) +// start_subregisters / ... 8/16/32-bit register forms +// start_symbolic / ... symbolic registers and memory hints +// start_fusion / ... xor-with-memory splitting + opt-in memory constraint +// Branches (jz/jnz) are not included: loop optimization on x86_64 is not yet safe. + +// Register aliases (.equ values may contain %) and memory offsets +.equ rState, %rdi +.equ rOut, %rsi +.equ _a, 1*8 +.equ _b, 2*8 +.equ _c, 3*8 +.equ _x, 4*8 +.equ _y, 6*8 + +start: + mov (rState), %rbx // mov_from_mem + mov _a(rState), %rax // mov_from_mem_offset + mov $3, %rcx // mov_qi + movq $5, %rdx // movq_i + add $1, %rax // add_qi + add %rbx, %rax // add_qq + and %rcx, %rax // and_qq + or %rdx, %rbx // or_qq + xor $7, %rbx // xor_qi + xor %rax, %rbx // xor_qq + not %rcx // not_q + rol $3, %rcx // rol_qi + rol %rdx // rol1 + shr $2, %rdx // shr_qi + sub $4, %rdx // sub_qi + xchg %rcx, %rdx // xchg_q: microcoded, uses every unit + mov %rcx, %r8 // mov_qq + movq %rdx, %r9 // movq + xor _b(rState), %r8 // xor_from_mem_offset: ALU0 + MEM + push %r9 // push: implicit rsp, uses every unit + pop %r10 // pop + mov %rax, (rOut) // mov_to_mem + mov %rbx, _a(rOut) // mov_to_mem_offset + xor %r8, _b(rOut) // xor_to_mem_offset + mov %r10, _c(rOut) + movdqu _x(rState), %xmm0 // movdqu_x_from_mem_offset + pxor _y(rState), %xmm0 // pxor_x_from_mem_offset: FP0 + MEM + pxor %xmm1, %xmm0 // pxor_xx + movdqu %xmm0, _x(rOut) // movdqu_x_to_mem_offset +end: + +// Sub-register forms on their own: overlap between e.g. al and rax is not modelled +start_subregisters: + add $1, %al // add_hi + add $1, %bx // add_si + add $1, %ecx // add_di + add %dl, %al // add_hh + add %si, %bx // add_ss + add %edi, %ecx // add_dd +end_subregisters: + +// Symbolic registers (allocated by SLOTHY) and a memory dependency declared by tags +start_symbolic: + mov _a(rState), %QW + mov _b(rState), %QW + xor %QW, %QW + rol $1, %QW + mov %QW, _a(rOut) // @slothy:writes=out + mov _a(rOut), %QW // @slothy:reads=out + add %QW, %QW + mov %QW, _b(rOut) +end_symbolic: + +// xor with a memory operand is split into a load and a register xor (fusion), then +// optimized with the opt-in Bonnell constraint: the load from _a(rState) and the +// store to _a(rOut) (same offset, different base register) stay 8 cycles apart +start_fusion: + xor _a(rState), %rax + xor _b(rState), %rbx + mov %rax, _a(rOut) + mov %rbx, _b(rOut) +end_fusion: diff --git a/examples/opt/x86_64/simple/x86_64_simple_opt_atom.s b/examples/opt/x86_64/simple/x86_64_simple_opt_atom.s new file mode 100644 index 000000000..71edee75f --- /dev/null +++ b/examples/opt/x86_64/simple/x86_64_simple_opt_atom.s @@ -0,0 +1,209 @@ +// x86_64 example for the Intel Atom (Bonnell) model, AT&T syntax. + +// Four regions, optimized separately (see _example.py): +// start / end every non-branch instruction form (selftest runs) +// start_subregisters / ... 8/16/32-bit register forms +// start_symbolic / ... symbolic registers and memory hints +// start_fusion / ... xor-with-memory splitting + opt-in memory constraint +// Branches (jz/jnz) are not included: loop optimization on x86_64 is not yet safe. + +// Register aliases (.equ values may contain %) and memory offsets +.equ rState, %rdi +.equ rOut, %rsi +.equ _a, 1*8 +.equ _b, 2*8 +.equ _c, 3*8 +.equ _x, 4*8 +.equ _y, 6*8 + + start: + // Instructions: 29 + // Expected cycles: 23 + // Expected IPC: 1.26 + // + // Cycle bound: 23.0 + // IPC bound: 1.26 + // + // Wall time: 0.04s + // User time: 0.04s + // + // ----- cycle (expected) ------> + // 0 25 + // |------------------------|---- + mov (%rdi), %r10 // *............................. + mov $3, %r11 // *............................. + mov 8(%rdi), %rbx // .*............................ + movq $5, %rcx // .*............................ + add $1, %rbx // ..*........................... + movdqu 32(%rdi), %xmm13 // ..*........................... + add %r10, %rbx // ...*.......................... + or %rcx, %r10 // ...*.......................... + and %r11, %rbx // ....*......................... + xor $7, %r10 // ....*......................... + xor %rbx, %r10 // .....*........................ + not %r11 // .....*........................ + rol $3, %r11 // ......*....................... + rol %rcx // .......*...................... + shr $2, %rcx // ........*..................... + pxor 48(%rdi), %xmm13 // ........*..................... + sub $4, %rcx // .........*.................... + mov %rbx, (%rsi) // .........*.................... + xchg %r11, %rcx // ..........*................... + mov %r11, %rbx // ................*............. + mov %r10, 8(%rsi) // ................*............. + xor 16(%rdi), %rbx // .................*............ + pxor %xmm1, %xmm13 // .................*............ + movq %rcx, %rcx // ..................*........... + xor %rbx, 16(%rsi) // ..................*........... + push %rcx // ...................*.......... + pop %r10 // ....................*......... + mov %r10, 24(%rsi) // .....................*........ + movdqu %xmm13, 32(%rsi) // ......................*....... + + // ------ cycle (expected) ------> + // 0 25 + // |------------------------|----- + // mov (%rdi), %rbx // *.............................. + // mov 1*8(%rdi), %rax // .*............................. + // mov $3, %rcx // *.............................. + // movq $5, %rdx // .*............................. + // add $1, %rax // ..*............................ + // add %rbx, %rax // ...*........................... + // and %rcx, %rax // ....*.......................... + // or %rdx, %rbx // ...*........................... + // xor $7, %rbx // ....*.......................... + // xor %rax, %rbx // .....*......................... + // not %rcx // .....*......................... + // rol $3, %rcx // ......*........................ + // rol %rdx // .......*....................... + // shr $2, %rdx // ........*...................... + // sub $4, %rdx // .........*..................... + // xchg %rcx, %rdx // ..........*.................... + // mov %rcx, %r8 // ................*.............. + // movq %rdx, %r9 // ..................*............ + // xor 2*8(%rdi), %r8 // .................*............. + // push %r9 // ...................*........... + // pop %r10 // ....................*.......... + // mov %rax, (%rsi) // .........*..................... + // mov %rbx, 1*8(%rsi) // ................*.............. + // xor %r8, 2*8(%rsi) // ..................*............ + // mov %r10, 3*8(%rsi) // .....................*......... + // movdqu 4*8(%rdi), %xmm0 // ..*............................ + // pxor 6*8(%rdi), %xmm0 // ........*...................... + // pxor %xmm1, %xmm0 // .................*............. + // movdqu %xmm0, 4*8(%rsi) // ......................*........ + + end: + + +// Sub-register forms on their own: overlap between e.g. al and rax is not modelled + start_subregisters: + // Instructions: 6 + // Expected cycles: 3 + // Expected IPC: 2.00 + // + // Cycle bound: 3.0 + // IPC bound: 2.00 + // + // Wall time: 0.01s + // User time: 0.01s + // + // ----- cycle (expected) ------> + // 0 25 + // |------------------------|---- + add $1, %al // *............................. + add $1, %bx // *............................. + add %dl, %al // .*............................ + add $1, %ecx // .*............................ + add %si, %bx // ..*........................... + add %edi, %ecx // ..*........................... + + // ------ cycle (expected) ------> + // 0 25 + // |------------------------|----- + // add $1, %al // *.............................. + // add $1, %bx // *.............................. + // add $1, %ecx // .*............................. + // add %dl, %al // .*............................. + // add %si, %bx // ..*............................ + // add %edi, %ecx // ..*............................ + + end_subregisters: + + +// Symbolic registers (allocated by SLOTHY) and a memory dependency declared by tags + start_symbolic: + // Instructions: 8 + // Expected cycles: 8 + // Expected IPC: 1.00 + // + // Cycle bound: 8.0 + // IPC bound: 1.00 + // + // Wall time: 0.01s + // User time: 0.01s + // + // ----- cycle (expected) ------> + // 0 25 + // |------------------------|---- + mov 8(%rdi), %rcx // *............................. + mov 16(%rdi), %r10 // .*............................ + xor %r10, %rcx // ..*........................... + rol $1, %rcx // ...*.......................... + mov %rcx, 8(%rsi) // ....*......................... // @slothy:writes=out + mov 8(%rsi), %rbx // .....*........................ // @slothy:reads=out + add %rbx, %rcx // ......*....................... + mov %rcx, 16(%rsi) // .......*...................... + + // ------ cycle (expected) ------> + // 0 25 + // |------------------------|----- + // mov 1*8(%rdi), %QW // *.............................. + // mov 2*8(%rdi), %QW // .*............................. + // xor %QW, %QW // ..*............................ + // rol $1, %QW // ...*........................... + // mov %QW, 1*8(%rsi) // ....*.......................... + // mov 1*8(%rsi), %QW // .....*......................... + // add %QW, %QW // ......*........................ + // mov %QW, 2*8(%rsi) // .......*....................... + + end_symbolic: + + +// xor with a memory operand is split into a load and a register xor (fusion), then +// optimized with the opt-in Bonnell constraint: the load from _a(rState) and the +// store to _a(rOut) (same offset, different base register) stay 8 cycles apart + start_fusion: + // Instructions: 6 + // Expected cycles: 10 + // Expected IPC: 0.60 + // + // Cycle bound: 10.0 + // IPC bound: 0.60 + // + // Wall time: 0.02s + // User time: 0.02s + // + // ----- cycle (expected) ------> + // 0 25 + // |------------------------|---- + mov 8(%rdi), %rcx // *............................. + xor %rcx, %rax // .*............................ + mov 16(%rdi), %r10 // .*............................ + xor %r10, %rbx // ..*........................... + mov %rax, 8(%rsi) // ........*..................... + mov %rbx, 16(%rsi) // .........*.................... + + // ------ cycle (expected) ------> + // 0 25 + // |------------------------|----- + // mov 8(%rdi), %QW // *.............................. + // xor %QW, %rax // .*............................. + // mov 16(%rdi), %QW // .*............................. + // xor %QW, %rbx // ..*............................ + // mov %rax, 8(%rsi) // ........*...................... + // mov %rbx, 16(%rsi) // .........*..................... + + end_fusion: + + diff --git a/slothy/helper.py b/slothy/helper.py index 7159fc7a6..d3e0134fe 100644 --- a/slothy/helper.py +++ b/slothy/helper.py @@ -705,7 +705,7 @@ class AsmAllocation: # handled in its own class. _REGEXP_EQU_TXT = ( r"\s*\.equ\s+(?P[_a-zA-Z][_a-zA-Z0-9]*)\s*," - r"\s*(?P[A-Za-z0-9()*/+\-\_\s]+)" + r"\s*(?P[A-Za-z0-9()*/+\-\_\s\%]+)" ) _REGEXP_REQ_TXT = r"\s*(?P\w+)\s+\.req\s+(?P\w+)" diff --git a/slothy/targets/query.py b/slothy/targets/query.py index c74f97158..11b56bd47 100644 --- a/slothy/targets/query.py +++ b/slothy/targets/query.py @@ -55,6 +55,9 @@ from slothy.targets.riscv import riscv as Arch_RISC_V from slothy.targets.riscv import xuantie_c908 as Target_XuanTie_C908 +from slothy.targets.x86_64 import x86_64 as Arch_X86_64 +from slothy.targets.x86_64 import intel_atom as Target_Intel_Atom + class UnknownTarget(Exception): """Exception raised when an unknown architecture or microarchitecture @@ -69,6 +72,7 @@ class Archery: "Arm_v81M": Arch_Armv81M, "Arm_AArch64": AArch64_Neon, "RISC_V": Arch_RISC_V, + "X86_64": Arch_X86_64, } _targets = { @@ -83,6 +87,7 @@ class Archery: "Apple_M1_firestorm_experimental": Target_AppleM1_Firestorm_Experimental, "Apple_M1_icestorm_experimental": Target_AppleM1_Icestorm_Experimental, "XuanTie_C908": Target_XuanTie_C908, + "Intel_Atom": Target_Intel_Atom, } @staticmethod diff --git a/slothy/targets/x86_64/__init__.py b/slothy/targets/x86_64/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/slothy/targets/x86_64/instruction_core.py b/slothy/targets/x86_64/instruction_core.py new file mode 100644 index 000000000..75b7b8fdc --- /dev/null +++ b/slothy/targets/x86_64/instruction_core.py @@ -0,0 +1,301 @@ +# +# Copyright (c) 2026 Maggie Simmons +# Copyright (c) 2026 Hayden Parsons +# SPDX-License-Identifier: MIT +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. +# + +""" +Generic instruction base class underlying the SLOTHY x86_64 instruction model +""" + +import logging +import re + +from slothy.targets.exceptions import FatalParsingException, ParsingException + + +class Instruction: + def __init__( + self, *, mnemonic, arg_types_in=None, arg_types_in_out=None, arg_types_out=None + ): + + if arg_types_in is None: + arg_types_in = [] + if arg_types_out is None: + arg_types_out = [] + if arg_types_in_out is None: + arg_types_in_out = [] + + self.mnemonic = mnemonic + + self.args_out_combinations = None + self.args_in_combinations = None + self.args_in_out_combinations = None + self.args_in_out_different = None + self.args_in_inout_different = None + + self.arg_types_in = arg_types_in + self.arg_types_out = arg_types_out + self.arg_types_in_out = arg_types_in_out + self.num_in = len(arg_types_in) + self.num_out = len(arg_types_out) + self.num_in_out = len(arg_types_in_out) + + self.args_out_restrictions = [None for _ in range(self.num_out)] + self.args_in_restrictions = [None for _ in range(self.num_in)] + self.args_in_out_restrictions = [None for _ in range(self.num_in_out)] + + self.args_in = [] + self.args_out = [] + self.args_in_out = [] + + self.addr = None + self.increment = None + self.pre_index = None + self.offset_adjustable = True + + self.immediate = None + self.offset = None + self.datatype = None + self.index = None + self.flag = None + self.barrel = None + self.label = None + + def extract_read_writes(self): + """Extracts 'reads'/'writes' clauses from the source line of the instruction""" + + from slothy.targets.x86_64.x86_64 import RegisterType + + src_line = self.source_line + + def hint_register_name(tag): + return f"hint_{tag}" + + # Check if the source line is tagged as reading/writing from memory + def add_memory_write(tag): + self.num_out += 1 + self.args_out_restrictions.append(None) + self.args_out.append(hint_register_name(tag)) + self.arg_types_out.append(RegisterType.HINT) + + def add_memory_read(tag): + self.num_in += 1 + self.args_in_restrictions.append(None) + self.args_in.append(hint_register_name(tag)) + self.arg_types_in.append(RegisterType.HINT) + + write_tags = src_line.tags.get("writes", []) + read_tags = src_line.tags.get("reads", []) + + if not isinstance(write_tags, list): + write_tags = [write_tags] + + if not isinstance(read_tags, list): + read_tags = [read_tags] + + for w in write_tags: + add_memory_write(w) + + for r in read_tags: + add_memory_read(r) + + return self + + def global_parsing_cb(self, a, log=None): + """Parsing callback triggered after DataFlowGraph parsing which allows + modification of the instruction in the context of the overall computation. + + This is primarily used to remodel input-outputs as outputs in jointly destructive + instruction patterns (See Section 4.4, https://eprint.iacr.org/2022/1303.pdf). + """ + _ = log # log is not used + return False + + def global_fusion_cb(self, a, log=None): + """Fusion callback triggered after DataFlowGraph parsing which allows fusing + of the instruction in the context of the overall computation. + + This can be used e.g. to detect eor-eor pairs and replace them by eor3.""" + _ = log # log is not used + return False + + def write(self): + """Write the instruction""" + args = self.args_in + self.args_in_out + self.args_out + return self.mnemonic + " " + ", ".join(args) + + def _is_instance_of(self, inst_list): + for inst in inst_list: + if isinstance(self, inst): + return True + return False + + # scalar or vector + def is_load(self): + """Indicates if an instruction is a load instruction""" + return False + + def is_store(self): + """Indicates if an instruction is a store instruction""" + return False + + def is_load_store_instruction(self): + """Indicates if an instruction is a scalar or Neon load or store instruction""" + return self.is_load() or self.is_store() + + @classmethod + def make(cls, src): + """Abstract factory method parsing a string into an instruction instance.""" + + @staticmethod + def build( # noqa: DOC103 + c: any, src: str, mnemonic: str, **kwargs: list + ) -> "Instruction": + """Attempt to parse a string as an instance of an instruction. + + :param c: The target instruction the string should be attempted to be parsed as. + :type c: any + :param src: The string to parse. + :type src: str + :param mnemonic: The mnemonic of instruction c + :type mnemonic: str + :param ``**kwargs``: Additional arguments to pass to the constructor of c. + :type ``**kwargs``: list + + :return: Upon success, the result of parsing src as an instance of c. + :rtype: Instruction + + :raises ParsingException: The str argument cannot be parsed as an + instance of c. + :raises FatalParsingException: A fatal error during parsing happened + that's likely a bug in the model. + """ + + if src.split(" ")[0] != mnemonic: + raise ParsingException("Mnemonic does not match") + + obj = c(mnemonic=mnemonic, **kwargs) + + expected_args = obj.num_in + obj.num_out + obj.num_in_out + regexp_txt = rf"^\s*{mnemonic}" + if expected_args > 0: + regexp_txt += r"\s+" + regexp_txt += ",".join([r"\s*(\w+)\s*" for _ in range(expected_args)]) + regexp = re.compile(regexp_txt) + + p = regexp.match(src) + if p is None: + raise ParsingException( + f"Doesn't match basic instruction template {regexp_txt}" + ) + + operands = list(p.groups()) + + if obj.num_out > 0: + obj.args_out = operands[: obj.num_out] + idx_args_in = obj.num_out + elif obj.num_in_out > 0: + obj.args_in_out = operands[: obj.num_in_out] + idx_args_in = obj.num_in_out + else: + idx_args_in = 0 + + obj.args_in = operands[idx_args_in:] + + if not len(obj.args_in) == obj.num_in: + raise FatalParsingException( + f"Something wrong parsing {src}: Expect {obj.num_in} input," + f" but got {len(obj.args_in)} ({obj.args_in})" + ) + + return obj + + @staticmethod + def parser(src_line): + """Global factory method parsing an assembly line into an instance + of a subclass of Instruction.""" + insts = [] + exceptions = {} + instnames = [] + + src = src_line.text.strip() + + # Iterate through all derived classes and call their parser + # until one of them hopefully succeeds + for inst_class in Instruction.all_subclass_leaves: + try: + inst = inst_class.make(src) + instnames = [inst_class.__name__] + insts = [inst] + break + except ParsingException as e: + exceptions[inst_class.__name__] = e + + for i in insts: + i.source_line = src_line + i.extract_read_writes() + + if len(insts) == 0: + logging.error("Failed to parse instruction %s", src) + logging.error("A list of attempted parsers and their exceptions follows.") + for i, e in exceptions.items(): + msg = f"* {i + ':':20s} {e}" + logging.error(msg) + raise ParsingException( + f"Couldn't parse {src}\nYou may need to add support " + "for a new instruction (variant)?" + ) + + logging.debug("Parsing result for '%s': %s", src, instnames) + return insts + + def __repr__(self): + return self.write() + + +# Returns the list of all subclasses of a class which don't have +# subclasses themselves +def all_subclass_leaves(c): + + def has_subclasses(cl): + return len(cl.__subclasses__()) > 0 + + def is_leaf(c): + return not has_subclasses(c) + + def all_subclass_leaves_core(leaf_lst, todo_lst): + leaf_lst += filter(is_leaf, todo_lst) + todo_lst = [ + csub + for c in filter(has_subclasses, todo_lst) + for csub in c.__subclasses__() + ] + if len(todo_lst) == 0: + return leaf_lst + return all_subclass_leaves_core(leaf_lst, todo_lst) + + return all_subclass_leaves_core([], [c]) + + +# The parser walks this precomputed list, so every module defining concrete +# instruction classes re-runs this assignment once its classes are in place. +Instruction.all_subclass_leaves = all_subclass_leaves(Instruction) diff --git a/slothy/targets/x86_64/intel_atom.py b/slothy/targets/x86_64/intel_atom.py new file mode 100644 index 000000000..98ca5f349 --- /dev/null +++ b/slothy/targets/x86_64/intel_atom.py @@ -0,0 +1,353 @@ +# +# Copyright (c) 2026 Maggie Simmons +# Copyright (c) 2026 Hayden Parsons +# SPDX-License-Identifier: MIT +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. +# + +from enum import Enum +from slothy.helper import lookup_multidict +from slothy.targets.x86_64.x86_64 import find_class +from slothy.targets.x86_64.x86_64_base_instructions import ( + add_hi, + add_si, + add_di, + add_qi, + add_hh, + add_ss, + add_dd, + add_qq, + and_qq, + jnz, + jz, + mov_qi, + mov_qq, + movq, + movq_i, + mov_from_mem, + mov_from_mem_offset, + mov_to_mem, + mov_to_mem_offset, + not_q, + or_qq, + pop, + push, + rol_qi, + rol1, + shr_qi, + sub_qi, + test_qi, + xchg_q, + xor_qi, + xor_qq, + xor_from_mem_offset, + xor_to_mem_offset, +) +from slothy.targets.x86_64.x86_64_sse_instructions import ( + movdqu_x_from_mem_offset, + movdqu_x_to_mem_offset, + pxor_x_from_mem_offset, + pxor_xx, +) +from slothy.targets.x86_64.x86_64_avx_instructions import ( # noqa: F401 + vpunpcklqdq_yyy, +) + +issue_rate = 2 +llvm_mca_target = "atom" + + +class ExecutionUnit(Enum): + """Enumeration of execution units in intel Atom model""" + + ALU0 = 1 + ALU1 = 2 + MUL = 3 + DIV = 4 + MEM = 5 + FP0 = 6 + FP1 = 7 + + def __repr__(self): + return self.name + + @classmethod + def SCALAR(cls): + """All scalar execution units""" + return [ExecutionUnit.ALU0, ExecutionUnit.ALU1] + + @classmethod + def SCALAR_MUL(cls): + """All multiply-capable scalar execution units""" + return [ExecutionUnit.MUL] + + +# Opt-in constraint for a Bonnell memory-access quirk (h2parson, 97d697b): memory +# accesses with the same immediate offset but different base registers that issue +# fewer than 8 cycles apart stalled on hardware more than predicted. On average this +# made SLOTHY's predictions more accurate and stall counts lower, but it is an +# oversimplification of the real behaviour and should be reformulated once its root +# cause is understood, so it is off by default. Enable with +# slothy.targets.x86_64.intel_atom.memory_offset_constraint = True +memory_offset_constraint = False +MEMORY_OFFSET_CYCLE_BUFFER = 8 + + +# Opaque function called by SLOTHY to add further microarchitecture- +# specific constraints which are not encapsulated by the general framework. +def add_further_constraints(slothy): + if slothy.config.constraints.functional_only: + return + if not memory_offset_constraint: + return + + from itertools import combinations, product + + from sympy import simplify + + def offset_key(offset): + # Compare offsets by value: 16(%rdi) and 2*8(%rsp) have the same offset + try: + return str(simplify(offset)) + except Exception: + return offset.strip() + + # Start-cycle variables of memory accesses, keyed by offset and base register + offset_dict = {} + for node in slothy._model.tree.nodes: + inst = node.inst + offset = getattr(inst, "offset", None) + if offset is not None: + addr = getattr(inst, "addr", None) + offset_dict.setdefault(offset_key(offset), {}).setdefault(addr, []).append( + node.cycle_start_var + ) + + model = slothy._model.cp_model + cycle_buffer = MEMORY_OFFSET_CYCLE_BUFFER + + # Pairs of instructions with the same offset but distinct base registers are at + # least cycle_buffer cycles apart + for addr_dict in offset_dict.values(): + for addr1, addr2 in combinations(list(addr_dict.keys()), 2): + for x, y in product(addr_dict[addr1], addr_dict[addr2]): + b = model.NewBoolVar("") + model.Add(x - y >= cycle_buffer).OnlyEnforceIf(b) + model.Add(y - x >= cycle_buffer).OnlyEnforceIf(b.Not()) + + +def has_min_max_objective(config): + _ = config + return False + + +def get_min_max_objective(slothy): + _ = slothy + return + + +execution_units = { + # Microcoded; measured inverse throughput 6 (see inverse_throughput), so model it + # as occupying every execution unit + (xchg_q,): [[unit for unit in ExecutionUnit]], + ( + rol_qi, + rol1, + rol_qi, + shr_qi, + ): [ + ExecutionUnit.ALU0, + ], + ( + jnz, + jz, + ): [ + ExecutionUnit.ALU1, + ], + ( + movdqu_x_from_mem_offset, + movdqu_x_to_mem_offset, + ): [ExecutionUnit.MEM], + ( + add_hi, + add_si, + add_di, + add_qi, + add_hh, + add_ss, + add_dd, + add_qq, + and_qq, + mov_qi, + mov_qq, + movq, + movq_i, + not_q, + or_qq, + sub_qi, + test_qi, + xor_qi, + xor_qq, + ): [ + ExecutionUnit.ALU0, + ExecutionUnit.ALU1, + ], + (pxor_xx,): [ + ExecutionUnit.FP0, + ExecutionUnit.FP1, + ], + ( + mov_from_mem, + mov_from_mem_offset, + mov_to_mem, + mov_to_mem_offset, + xor_from_mem_offset, + xor_to_mem_offset, + ): [[ExecutionUnit.ALU0, ExecutionUnit.MEM]], + # Needs the MEM unit and an FP unit. Modelled as FP0 + MEM only: a choice between + # groups ([[FP0, MEM], [FP1, MEM]]) is not supported by SLOTHY's unit model + (pxor_x_from_mem_offset,): [[ExecutionUnit.FP0, ExecutionUnit.MEM]], + ( + pop, + push, + ): [ + [ + unit for unit in ExecutionUnit + ] # Not pairable so model as using every execution unit + ], +} + +inverse_throughput = { + ( + add_hi, + add_si, + add_di, + add_qi, + add_hh, + add_ss, + add_dd, + add_qq, + and_qq, + mov_qi, + mov_qq, + movq, + movq_i, + mov_from_mem, + mov_from_mem_offset, + mov_to_mem, + mov_to_mem_offset, + not_q, + or_qq, + pop, + push, + pxor_x_from_mem_offset, + pxor_xx, + rol_qi, + rol1, + rol_qi, + shr_qi, + sub_qi, + test_qi, + xor_qi, + xor_qq, + xor_from_mem_offset, + xor_to_mem_offset, + ): 1, + ( + jnz, + jz, + ): 2, + ( + movdqu_x_from_mem_offset, + movdqu_x_to_mem_offset, + xchg_q, + ): 6, +} + +default_latencies = { + ( + jnz, + jz, + ): 0, + ( + add_hi, + add_si, + add_di, + add_qi, + add_hh, + add_ss, + add_dd, + add_qq, + and_qq, + mov_qi, + mov_qq, + movq, + movq_i, + mov_from_mem, + mov_from_mem_offset, + mov_to_mem, + mov_to_mem_offset, + not_q, + or_qq, + pop, + push, + pxor_x_from_mem_offset, + pxor_xx, + rol_qi, + rol1, + rol_qi, + shr_qi, + sub_qi, + test_qi, + xor_qi, + xor_qq, + xor_from_mem_offset, + xor_to_mem_offset, + ): 1, + ( + movdqu_x_from_mem_offset, + movdqu_x_to_mem_offset, + xchg_q, + ): 6, +} + + +def get_latency(src, out_idx, dst): + _ = out_idx + _ = dst + + instclass_src = find_class(src) + + latency = lookup_multidict(default_latencies, src, instclass_src) + + return latency + + +def get_units(src): + instclass_src = find_class(src) + units = lookup_multidict(execution_units, src, instclass_src) + if isinstance(units, list): + return units + return [units] + + +def get_inverse_throughput(src): + instclass_src = find_class(src) + return lookup_multidict(inverse_throughput, src, instclass_src) diff --git a/slothy/targets/x86_64/x86_64.py b/slothy/targets/x86_64/x86_64.py new file mode 100644 index 000000000..0079c46e5 --- /dev/null +++ b/slothy/targets/x86_64/x86_64.py @@ -0,0 +1,793 @@ +# +# Copyright (c) 2026 Maggie Simmons +# Copyright (c) 2026 Hayden Parsons +# SPDX-License-Identifier: MIT +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. +# + +""" +Partial SLOTHY architecture model for x86_64 +""" + +import logging +import re +from enum import Enum +from functools import cache +from sympy import simplify + +from unicorn import ( + UC_ARCH_X86, + UC_MODE_64, +) + + +from unicorn.x86_const import ( + UC_X86_REG_AH, + UC_X86_REG_AL, + UC_X86_REG_AX, + UC_X86_REG_BH, + UC_X86_REG_BL, + UC_X86_REG_BP, + UC_X86_REG_BPL, + UC_X86_REG_BX, + UC_X86_REG_CH, + UC_X86_REG_CL, + UC_X86_REG_CS, + UC_X86_REG_CX, + UC_X86_REG_DH, + UC_X86_REG_DI, + UC_X86_REG_DIL, + UC_X86_REG_DL, + UC_X86_REG_DS, + UC_X86_REG_DX, + UC_X86_REG_EAX, + UC_X86_REG_EBP, + UC_X86_REG_EBX, + UC_X86_REG_ECX, + UC_X86_REG_EDI, + UC_X86_REG_EDX, + UC_X86_REG_ES, + UC_X86_REG_ESI, + UC_X86_REG_ESP, + UC_X86_REG_IP, + UC_X86_REG_RAX, + UC_X86_REG_RBP, + UC_X86_REG_RBX, + UC_X86_REG_RCX, + UC_X86_REG_RDI, + UC_X86_REG_RDX, + UC_X86_REG_RIP, + UC_X86_REG_RSI, + UC_X86_REG_RSP, + UC_X86_REG_SI, + UC_X86_REG_SIL, + UC_X86_REG_SP, + UC_X86_REG_SPL, + UC_X86_REG_MM0, + UC_X86_REG_MM1, + UC_X86_REG_MM2, + UC_X86_REG_MM3, + UC_X86_REG_MM4, + UC_X86_REG_MM5, + UC_X86_REG_MM6, + UC_X86_REG_MM7, + UC_X86_REG_R8, + UC_X86_REG_R9, + UC_X86_REG_R10, + UC_X86_REG_R11, + UC_X86_REG_R12, + UC_X86_REG_R13, + UC_X86_REG_R14, + UC_X86_REG_R15, + UC_X86_REG_XMM0, + UC_X86_REG_XMM1, + UC_X86_REG_XMM2, + UC_X86_REG_XMM3, + UC_X86_REG_XMM4, + UC_X86_REG_XMM5, + UC_X86_REG_XMM6, + UC_X86_REG_XMM7, + UC_X86_REG_XMM8, + UC_X86_REG_XMM9, + UC_X86_REG_XMM10, + UC_X86_REG_XMM11, + UC_X86_REG_XMM12, + UC_X86_REG_XMM13, + UC_X86_REG_XMM14, + UC_X86_REG_XMM15, + UC_X86_REG_XMM16, + UC_X86_REG_XMM17, + UC_X86_REG_XMM18, + UC_X86_REG_XMM19, + UC_X86_REG_XMM20, + UC_X86_REG_XMM21, + UC_X86_REG_XMM22, + UC_X86_REG_XMM23, + UC_X86_REG_XMM24, + UC_X86_REG_XMM25, + UC_X86_REG_XMM26, + UC_X86_REG_XMM27, + UC_X86_REG_XMM28, + UC_X86_REG_XMM29, + UC_X86_REG_XMM30, + UC_X86_REG_XMM31, + UC_X86_REG_YMM0, + UC_X86_REG_YMM1, + UC_X86_REG_YMM2, + UC_X86_REG_YMM3, + UC_X86_REG_YMM4, + UC_X86_REG_YMM5, + UC_X86_REG_YMM6, + UC_X86_REG_YMM7, + UC_X86_REG_YMM8, + UC_X86_REG_YMM9, + UC_X86_REG_YMM10, + UC_X86_REG_YMM11, + UC_X86_REG_YMM12, + UC_X86_REG_YMM13, + UC_X86_REG_YMM14, + UC_X86_REG_YMM15, + UC_X86_REG_YMM16, + UC_X86_REG_YMM17, + UC_X86_REG_YMM18, + UC_X86_REG_YMM19, + UC_X86_REG_YMM20, + UC_X86_REG_YMM21, + UC_X86_REG_YMM22, + UC_X86_REG_YMM23, + UC_X86_REG_YMM24, + UC_X86_REG_YMM25, + UC_X86_REG_YMM26, + UC_X86_REG_YMM27, + UC_X86_REG_YMM28, + UC_X86_REG_YMM29, + UC_X86_REG_YMM30, + UC_X86_REG_YMM31, + UC_X86_REG_ZMM0, + UC_X86_REG_ZMM1, + UC_X86_REG_ZMM2, + UC_X86_REG_ZMM3, + UC_X86_REG_ZMM4, + UC_X86_REG_ZMM5, + UC_X86_REG_ZMM6, + UC_X86_REG_ZMM7, + UC_X86_REG_ZMM8, + UC_X86_REG_ZMM9, + UC_X86_REG_ZMM10, + UC_X86_REG_ZMM11, + UC_X86_REG_ZMM12, + UC_X86_REG_ZMM13, + UC_X86_REG_ZMM14, + UC_X86_REG_ZMM15, + UC_X86_REG_ZMM16, + UC_X86_REG_ZMM17, + UC_X86_REG_ZMM18, + UC_X86_REG_ZMM19, + UC_X86_REG_ZMM20, + UC_X86_REG_ZMM21, + UC_X86_REG_ZMM22, + UC_X86_REG_ZMM23, + UC_X86_REG_ZMM24, + UC_X86_REG_ZMM25, + UC_X86_REG_ZMM26, + UC_X86_REG_ZMM27, + UC_X86_REG_ZMM28, + UC_X86_REG_ZMM29, + UC_X86_REG_ZMM30, + UC_X86_REG_ZMM31, + UC_X86_REG_R8B, + UC_X86_REG_R9B, + UC_X86_REG_R10B, + UC_X86_REG_R11B, + UC_X86_REG_R12B, + UC_X86_REG_R13B, + UC_X86_REG_R14B, + UC_X86_REG_R15B, + UC_X86_REG_R8D, + UC_X86_REG_R9D, + UC_X86_REG_R10D, + UC_X86_REG_R11D, + UC_X86_REG_R12D, + UC_X86_REG_R13D, + UC_X86_REG_R14D, + UC_X86_REG_R15D, + UC_X86_REG_R8W, + UC_X86_REG_R9W, + UC_X86_REG_R10W, + UC_X86_REG_R11W, + UC_X86_REG_R12W, + UC_X86_REG_R13W, + UC_X86_REG_R14W, + UC_X86_REG_R15W, + UC_X86_REG_FLAGS, +) + +from slothy.targets.exceptions import ( + FatalParsingException, + UnknownInstruction, +) +from slothy.helper import Loop +from slothy.targets.x86_64.instruction_core import Instruction, all_subclass_leaves + +unicorn_arch = UC_ARCH_X86 +unicorn_mode = UC_MODE_64 + +arch_name = "x86_64" + +llvm_mca_arch = "x86-64" +llvm_mc_arch = "x86-64" +llvm_mc_attr = "" + + +class SymbolicRegister(str): + """Name of a symbolic register, e.g. 'state' for QW. + + Kept distinct from plain register IDs ('a' for rax, '8' for r8, ...) so that + symbolic names which look like IDs are not turned into physical registers.""" + + +class RegisterType(Enum): + GPR_H = 1 + GPR_S = 2 + GPR_D = 3 + GPR_Q = 4 + + XMM = 5 + YMM = 6 + + FLAGS = 7 + + # Pseudo-registers for memory dependencies declared via reads=/writes= tags + HINT = 8 + + def __str__(self): + return self.name + + def __repr__(self): + return self.name + + @staticmethod + @cache + def spillable(reg_type): + return reg_type in [RegisterType.GPR] # For now, only GPRs + + @staticmethod + def callee_saved_registers(): + return [f"x{i}" for i in range(18, 31)] + [f"v{i}" for i in range(8, 16)] + + @staticmethod + def unicorn_link_register(): + return None + + @staticmethod + def unicorn_stack_pointer(): + return UC_X86_REG_SP + + @staticmethod + def unicorn_program_counter(): + return UC_X86_REG_IP + + @staticmethod + @cache + def unicorn_reg_by_name(reg): + """Converts string name of register into numerical identifiers used + within the unicorn engine""" + + d = { + "ah": UC_X86_REG_AH, + "al": UC_X86_REG_AL, + "ax": UC_X86_REG_AX, + "bh": UC_X86_REG_BH, + "bl": UC_X86_REG_BL, + "bp": UC_X86_REG_BP, + "bpl": UC_X86_REG_BPL, + "bx": UC_X86_REG_BX, + "ch": UC_X86_REG_CH, + "cl": UC_X86_REG_CL, + "cs": UC_X86_REG_CS, + "cx": UC_X86_REG_CX, + "dh": UC_X86_REG_DH, + "di": UC_X86_REG_DI, + "dil": UC_X86_REG_DIL, + "dl": UC_X86_REG_DL, + "ds": UC_X86_REG_DS, + "dx": UC_X86_REG_DX, + "eax": UC_X86_REG_EAX, + "ebp": UC_X86_REG_EBP, + "ebx": UC_X86_REG_EBX, + "ecx": UC_X86_REG_ECX, + "edi": UC_X86_REG_EDI, + "edx": UC_X86_REG_EDX, + "es": UC_X86_REG_ES, + "esi": UC_X86_REG_ESI, + "esp": UC_X86_REG_ESP, + "ip": UC_X86_REG_IP, + "rax": UC_X86_REG_RAX, + "rbp": UC_X86_REG_RBP, + "rbx": UC_X86_REG_RBX, + "rcx": UC_X86_REG_RCX, + "rdi": UC_X86_REG_RDI, + "rdx": UC_X86_REG_RDX, + "rip": UC_X86_REG_RIP, + "rsi": UC_X86_REG_RSI, + "rsp": UC_X86_REG_RSP, + "si": UC_X86_REG_SI, + "sil": UC_X86_REG_SIL, + "sp": UC_X86_REG_SP, + "spl": UC_X86_REG_SPL, + "mm0": UC_X86_REG_MM0, + "mm1": UC_X86_REG_MM1, + "mm2": UC_X86_REG_MM2, + "mm3": UC_X86_REG_MM3, + "mm4": UC_X86_REG_MM4, + "mm5": UC_X86_REG_MM5, + "mm6": UC_X86_REG_MM6, + "mm7": UC_X86_REG_MM7, + "r8": UC_X86_REG_R8, + "r9": UC_X86_REG_R9, + "r10": UC_X86_REG_R10, + "r11": UC_X86_REG_R11, + "r12": UC_X86_REG_R12, + "r13": UC_X86_REG_R13, + "r14": UC_X86_REG_R14, + "r15": UC_X86_REG_R15, + "xmm0": UC_X86_REG_XMM0, + "xmm1": UC_X86_REG_XMM1, + "xmm2": UC_X86_REG_XMM2, + "xmm3": UC_X86_REG_XMM3, + "xmm4": UC_X86_REG_XMM4, + "xmm5": UC_X86_REG_XMM5, + "xmm6": UC_X86_REG_XMM6, + "xmm7": UC_X86_REG_XMM7, + "xmm8": UC_X86_REG_XMM8, + "xmm9": UC_X86_REG_XMM9, + "xmm10": UC_X86_REG_XMM10, + "xmm11": UC_X86_REG_XMM11, + "xmm12": UC_X86_REG_XMM12, + "xmm13": UC_X86_REG_XMM13, + "xmm14": UC_X86_REG_XMM14, + "xmm15": UC_X86_REG_XMM15, + "xmm16": UC_X86_REG_XMM16, + "xmm17": UC_X86_REG_XMM17, + "xmm18": UC_X86_REG_XMM18, + "xmm19": UC_X86_REG_XMM19, + "xmm20": UC_X86_REG_XMM20, + "xmm21": UC_X86_REG_XMM21, + "xmm22": UC_X86_REG_XMM22, + "xmm23": UC_X86_REG_XMM23, + "xmm24": UC_X86_REG_XMM24, + "xmm25": UC_X86_REG_XMM25, + "xmm26": UC_X86_REG_XMM26, + "xmm27": UC_X86_REG_XMM27, + "xmm28": UC_X86_REG_XMM28, + "xmm29": UC_X86_REG_XMM29, + "xmm30": UC_X86_REG_XMM30, + "xmm31": UC_X86_REG_XMM31, + "ymm0": UC_X86_REG_YMM0, + "ymm1": UC_X86_REG_YMM1, + "ymm2": UC_X86_REG_YMM2, + "ymm3": UC_X86_REG_YMM3, + "ymm4": UC_X86_REG_YMM4, + "ymm5": UC_X86_REG_YMM5, + "ymm6": UC_X86_REG_YMM6, + "ymm7": UC_X86_REG_YMM7, + "ymm8": UC_X86_REG_YMM8, + "ymm9": UC_X86_REG_YMM9, + "ymm10": UC_X86_REG_YMM10, + "ymm11": UC_X86_REG_YMM11, + "ymm12": UC_X86_REG_YMM12, + "ymm13": UC_X86_REG_YMM13, + "ymm14": UC_X86_REG_YMM14, + "ymm15": UC_X86_REG_YMM15, + "ymm16": UC_X86_REG_YMM16, + "ymm17": UC_X86_REG_YMM17, + "ymm18": UC_X86_REG_YMM18, + "ymm19": UC_X86_REG_YMM19, + "ymm20": UC_X86_REG_YMM20, + "ymm21": UC_X86_REG_YMM21, + "ymm22": UC_X86_REG_YMM22, + "ymm23": UC_X86_REG_YMM23, + "ymm24": UC_X86_REG_YMM24, + "ymm25": UC_X86_REG_YMM25, + "ymm26": UC_X86_REG_YMM26, + "ymm27": UC_X86_REG_YMM27, + "ymm28": UC_X86_REG_YMM28, + "ymm29": UC_X86_REG_YMM29, + "ymm30": UC_X86_REG_YMM30, + "ymm31": UC_X86_REG_YMM31, + "zmm0": UC_X86_REG_ZMM0, + "zmm1": UC_X86_REG_ZMM1, + "zmm2": UC_X86_REG_ZMM2, + "zmm3": UC_X86_REG_ZMM3, + "zmm4": UC_X86_REG_ZMM4, + "zmm5": UC_X86_REG_ZMM5, + "zmm6": UC_X86_REG_ZMM6, + "zmm7": UC_X86_REG_ZMM7, + "zmm8": UC_X86_REG_ZMM8, + "zmm9": UC_X86_REG_ZMM9, + "zmm10": UC_X86_REG_ZMM10, + "zmm11": UC_X86_REG_ZMM11, + "zmm12": UC_X86_REG_ZMM12, + "zmm13": UC_X86_REG_ZMM13, + "zmm14": UC_X86_REG_ZMM14, + "zmm15": UC_X86_REG_ZMM15, + "zmm16": UC_X86_REG_ZMM16, + "zmm17": UC_X86_REG_ZMM17, + "zmm18": UC_X86_REG_ZMM18, + "zmm19": UC_X86_REG_ZMM19, + "zmm20": UC_X86_REG_ZMM20, + "zmm21": UC_X86_REG_ZMM21, + "zmm22": UC_X86_REG_ZMM22, + "zmm23": UC_X86_REG_ZMM23, + "zmm24": UC_X86_REG_ZMM24, + "zmm25": UC_X86_REG_ZMM25, + "zmm26": UC_X86_REG_ZMM26, + "zmm27": UC_X86_REG_ZMM27, + "zmm28": UC_X86_REG_ZMM28, + "zmm29": UC_X86_REG_ZMM29, + "zmm30": UC_X86_REG_ZMM30, + "zmm31": UC_X86_REG_ZMM31, + "r8b": UC_X86_REG_R8B, + "r9b": UC_X86_REG_R9B, + "r10b": UC_X86_REG_R10B, + "r11b": UC_X86_REG_R11B, + "r12b": UC_X86_REG_R12B, + "r13b": UC_X86_REG_R13B, + "r14b": UC_X86_REG_R14B, + "r15b": UC_X86_REG_R15B, + "r8d": UC_X86_REG_R8D, + "r9d": UC_X86_REG_R9D, + "r10d": UC_X86_REG_R10D, + "r11d": UC_X86_REG_R11D, + "r12d": UC_X86_REG_R12D, + "r13d": UC_X86_REG_R13D, + "r14d": UC_X86_REG_R14D, + "r15d": UC_X86_REG_R15D, + "r8w": UC_X86_REG_R8W, + "r9w": UC_X86_REG_R9W, + "r10w": UC_X86_REG_R10W, + "r11w": UC_X86_REG_R11W, + "r12w": UC_X86_REG_R12W, + "r13w": UC_X86_REG_R13W, + "r14w": UC_X86_REG_R14W, + "r15w": UC_X86_REG_R15W, + "flags": UC_X86_REG_FLAGS, + } + return d.get(reg, None) + + @staticmethod + @cache + def list_byte_gprs(): + letter_labels = ["a", "b", "c", "d"] + return ( + [f"{p}l" for p in letter_labels] + + ["dil", "sil"] + + ["spl", "bpl"] + + [f"r{n}l" for n in range(8, 16)] + ) + + @staticmethod + @cache + def list_word_gprs(): + letter_labels = ["a", "b", "c", "d"] + return ( + [f"{p}x" for p in letter_labels] + + ["di", "si"] + + ["sp", "bp"] + + [f"r{n}w" for n in range(8, 16)] + ) + + @staticmethod + @cache + def list_dblword_gprs(): + letter_labels = ["a", "b", "c", "d"] + return ( + [f"e{p}x" for p in letter_labels] + + ["edi", "esi"] + + ["esp", "ebp"] + + [f"r{n}d" for n in range(8, 16)] + ) + + @staticmethod + @cache + def list_qdword_gprs(): + letter_labels = ["a", "b", "c", "d"] + return ( + [f"r{p}x" for p in letter_labels] + + ["rdi", "rsi"] + + ["rsp", "rbp"] + + [f"r{n}" for n in range(8, 16)] + ) + + @staticmethod + @cache + def list_xmm(): + return [f"xmm{n}" for n in range(16)] + + @staticmethod + @cache + def list_ymm(): + return [f"ymm{n}" for n in range(16)] + + @staticmethod + @cache + def list_flags(): + return ["SF", "ZF", "PF"] + + @staticmethod + @cache + def list_hints(): + return ( + [f"t{i}" for i in range(100)] + + [f"t{i}{j}" for i in range(8) for j in range(8)] + + [f"t{i}_{j}" for i in range(16) for j in range(16)] + ) + + @staticmethod + @cache + def list_registers( + reg_type, only_extra=False, only_normal=False, with_variants=False + ): + """Return the list of all registers of a given type""" + + return { + RegisterType.GPR_H: RegisterType.list_byte_gprs(), + RegisterType.GPR_S: RegisterType.list_word_gprs(), + RegisterType.GPR_D: RegisterType.list_dblword_gprs(), + RegisterType.GPR_Q: RegisterType.list_qdword_gprs(), + RegisterType.XMM: RegisterType.list_xmm(), + RegisterType.YMM: RegisterType.list_ymm(), + RegisterType.FLAGS: RegisterType.list_flags(), + RegisterType.HINT: RegisterType.list_hints(), + }[reg_type] + + @staticmethod + def find_type(r): + """Find type of architectural register""" + + if r.startswith("hint_"): + return RegisterType.HINT + + for ty in RegisterType: + if r in RegisterType.list_registers(ty): + return ty + + return None + + def reg_to_id(name): + # Anchored, so that e.g. rdi gives "di" rather than "d" (rdx) + regexp_text = ( + "(?:([eErR]|ymm|YMM|xmm|XMM)?" + "(?P([abcdABCD]|[sbSB][pP]|[sSdD][iI]|\\d[0-5]?))[lLwWdDxX]?" + "|\\w+<(?P\\w[\\w\\d_]*)>)\\Z" + ) + regexp = re.compile(regexp_text) + match = regexp.match(name) + if match is None: + raise FatalParsingException( + f"Cannot extract identifier from register name {name}!" + ) + if match.group("raw_ID") is not None: + return match.group("raw_ID") + elif match.group("symbol_ID") is not None: + return SymbolicRegister(match.group("symbol_ID")) + else: + raise FatalParsingException( + f"Cannot extract identifier from register name {name}!" + ) + + def type_to_pattern(ty, label): + s = "" + if ty == RegisterType.GPR_H: + s += "HW" + elif ty == RegisterType.GPR_S: + s += "SW" + elif ty == RegisterType.GPR_D: + s += "DW" + elif ty == RegisterType.GPR_Q: + s += "QW" + elif ty == RegisterType.XMM: + s += "XMM" + elif ty == RegisterType.YMM: + s += "YMM" + else: + raise FatalParsingException( + f"Type {ty.name} cannot be converted to pattern symbol" + ) + + s += label + return s + + @staticmethod + def is_renamed(ty): + """Indicate if register type should be subject to renaming""" + if ty == RegisterType.HINT: + return False + return True + + @staticmethod + def from_string(string): + """Find register type from string""" + string = string.lower() + return { + "gpr_h": RegisterType.GPR_H, + "gpr_s": RegisterType.GPR_S, + "gpr_d": RegisterType.GPR_D, + "gpr_q": RegisterType.GPR_Q, + "xmm": RegisterType.XMM, + "ymm": RegisterType.YMM, + "flags": RegisterType.FLAGS, + "hint": RegisterType.HINT, + }.get(string, None) + + # TODO: fill this in + @staticmethod + def default_reserved(): + """Return the list of registers that should be reserved by default""" + return set( + ["spl", "sp", "esp", "rsp", "bpl", "bp", "ebp", "rbp"] + + RegisterType.list_registers(RegisterType.HINT) + ) + + @staticmethod + def default_aliases(): + "Register aliases used by the architecture" + return {} + + +class BranchLoop(Loop): + """ + More general loop type that just considers the branch instruction as part + of the boundary. + This can help to improve performance as the instructions that belong to + handling the loop can be considered by SLOTHY as well. + + .. note:: + + This loop type is still rather experimental. It has a lot of logics + inside as it needs to be able to "understand" a variety of different + ways to express loops, e.g., how counters get incremented, how + registers marking the end of the + loop need to be modified in case of software pipelining etc. + + .. warning:: + + Loop optimization on x86_64 is currently UNSAFE and is being fixed. + Flag writes are only partially modelled: ``test`` writes SF/ZF/PF and + ``jz``/``jnz`` read ZF, but other flag-writing instructions (``add``, + ``sub``, ``and``, ``or``, ``xor``, ``shr``) don't declare their flag + writes. SLOTHY can therefore schedule one of them between the ``test`` + and the branch, which overwrites ZF on hardware and changes the loop's + control flow. The selftest does not catch this (it doesn't compare flags). + Straight-line code that doesn't read flags is not affected. + + """ + + def __init__(self, lbl="lbl") -> None: + super().__init__() + # The group naming in the regex should be consistent; give same group + # names to the same registers + self.lbl = lbl + self.lbl_regex = r"^\s*(?P