RIA-JIT aims to build a RISC-V emulator on x86-64 ISA machine, and take advantage of dynamic binary translation to provide a faster emulator, allowing the execution of RV64 on an x86–64 machine. Authors want to provide a tool to execute binaries compiled for RISC–V Linux on Linux for x86–64, what is conventionally called user space emulation, full system emulation is not supported. Currently only single threaded applications are supported, since managing the execution environment and guaranteeing atomicity for the respective instructions would be rather difficult.
Dynamic Binary Translation (DBT), which serves as a middle ground between interpreting and statically translating the executable. It aims to translate the program on the fly, while only focusing on the parts that are actually needed for execution. Therefore, it can save some of the overhead of a static translator by not spending execution time on unused code paths. The other issues are also fairly easily resolved. Unlike an interpreter, every instruction only has to be translated once and can then be run without any unnecessary overhead.
Our work is to understand the problems stated in the paper issued by project contributors, along with their solutions and implementation details.
Memory Access in RV64
RV64 is a 3-operand ISA with explicit load/store instructions
x86-64 is a 2-operand ISA with register-memory architecture(without load/store instructions)
This DBT is translating code from a three-operand instruction format into a register-memory architecture in which one of the source operands is also the implicit destination operand.
This means that the single arithmetic instruction sub rd, rs1, rs2
in RISC–V assembly language generally can not be translated via a single instruction, but rather requires two instructions: moving rs1
to rd
, then subtracting the value of rs2
from rd
.
This problem can be resolved by applying Instruction Fusion, for example, that an instruction like xori x10, x10, -1
can be directly translated as a not x10
, without needing to resort to mov
and xor
.
Immediate Loading in RV64
RV64 handles loading immediate in length of word or double word with multiple LUIs and ANDI/ORI
x86-64 can deal with MOV r/m64, imm
Same problem arising from difference between three-operand instruction and register-memory instruction is long immediate loading, which would take several RV64 instructions but the number of instructions can be reduced or even replaced by single x86 instruction with Instruction Fusion.
For example, an lui rd, imm1
followed by addi rd, rd, imm2
may for example be translated as directly loading the result of the computation imm1 + imm2
into rd
.
Number of General Purpose Registers
RV64 has 31 GPRs excluding x0
x86-64 has 16 GPRs and some of them have specific functions
Keeping a guest register file exclusively in memory, and loading them when needed within the translations of single instructions is technically possible. However, a large number of memory accesses for both memory operands in the instructions and local register allocation within the translated blocks is needed.
Thus, authors designed a tool and utilized it to determine register mapping, which is described in GPRs Mapping.
Register Handling
RV64 has 32 floating-point registers
x86-64 has 16 XMM registers
Same problem as GPRs in RV64 and x86-64, the RISC–V architecture consists of 32 floating point registers (f0–f31) which can hold a single precision (F-extension) or double precision (D-extension) floating point value, whereas the SSE-extensions only provide 16 registers XMM0–XMM15. The means of mapping 32 floating point registers to XMM registers is also described in GPRs Mapping.
Missing Corresponding Instructions in x86-64 for Fused Instruction in RV64
Because SSE extensions do not support immediate operands, constants or masks need to be loaded in from either memory or the general purpose registers can lead to huge overhead.
The instructions that need to be emulated are unsigned conversion instructions, e.g. FCVT.WU.S, sign-injection instructions, e.g. FSGNJ.S, compare instructions, e.g. FEQ.S, fused multiply-add instructions, e.g. FMADD.S and the FCLASS.S instruction that classifies a floating point value.
The solution is described in Using AVX extension or GCC Generated Code to Replace Fused Instruction Missing
Different Rounding Mode in x86-64 and RV64
Rounding modes are handled differently in the RISC–V architecture, as the rounding mode can be set individually for every instruction.
The solution is described in Temporary Alter Rounding Mode
Floating Point Exception Handling
Exception handling in RISC–V is realized by reading the fcsr
floating-point control and status register, traps are not supported. To prevent trap from occurring in host process, host needs to utilize MXCSR
multimedia extension control and status register, which is described in Intercept and Handle Exception in Run Time.
To suffice the characteristic of DBT, translator divides guest code into several basic blocks. Basic blocks, by definition, have only a single point of entry and exit; for our purposes, a basic block will be terminated by any control-flow altering instruction like a jump, call or return statement, or a system call.
To accelerate the generated code access, software-based code cache and TLB are designed by authors, but when dealing with code in huge size, code blocks might exceed code cache; thus, different proposed methods are described in InputGuest-Code-Partitioning-and-Caching1
For RISC–V, the instruction ECALL
handles system calls, with the system call number residing in register a7
and the arguments passed in a0
–a6
.
In order to handle the ECALL instruction correctly, the translator can usually build the translated instruction to call a specific handler routine with system calls that exist natively on the host architecture, i.e.: write
or clock_gettime
.
However, below are different types of things to be taken care of:
Resolving Penalties Stemming from Context Switches between Guest Code and Translation Loop
To reduce the performance penalties imposed by the concept of dynamic binary translation. Authors optimize control flow to avoid leaving guest context in several means mentioned in Optimization.
Taking Advantage of CISC ISA
To further increases execution efficiency of the generated arithmetic instructions, authors conduct the optimization by means of macro opcode fusion as Instruction Fusion mentioned.
Instruction Fusion
As RISC–V is a RISC and x86–64 a CISC architecture, programs often need more instructions on RISC–V than on x86–64 to achieve the same effect. Authors employed a technique known as macro operation fusion to translate specific patterns of RISC–V instructions into shorter, equivalent x86–64 code, thereby increasing performance of the generated code, and solved the memory access and immediate value loading issues.
There is a pattern matcher detecting these patterns after parsing, as the below source code located in src/gen/optimize.c
indicates. Once the pattern is matched, the mnemonic of the pattern would be noted as PATTERN_EMIT
, and use optype
to differentiate in patterns.
Patterns are stored in data structure given in src/gen/instr/patterns.c
as below. Each pattern contains pattern elements, number of elements and corresponding code emitter.
Taking pattern that can emit ADD32mi
for example, corresponding p_2_elem
contains below data, which represent load a whole 64-bit address, load a 32-bit data, add the data with immediate in fourth instruction and store the 32-bit data back.
After matching the above elements, code would be generated in below routine. If the address is 32-bit wide, the generated code is dealing with this action in "add 32-bit immediate to memory address", ADD32MI
. Otherwise, the address would be first load into RAX
register and later do the ADD32MI
.
GPRs Mapping
For shortness in the number of GPRs in x86-64 ISA, authors utilize the tools built by themselves in the translator to discover the most-used registers in the guest programs, and statically map these to general purpose x86–64 registers. The remaining operands are then dynamically allocated into reserved host registers inside the translation of a single block. The loaded values are then lazily kept in the temporary registers for as long as possible in order to avoid unnecessary memory accesses.
After their research, they found that it can covers the most use case to map GPRs and FP registers as below. As for RAX
, RCX
, RDX
, RSP
they are for temporary register mapping usage.
RISC–V register | x86–64 mapping |
---|---|
a5 | RBX |
a4 | RBP |
a3 | RSI |
a0 | RDI |
fp | R8 |
sp | R9 |
a2 | R10 |
a1 | R11 |
s1 | R12 |
ra | R13 |
a7 | R14 |
s2 | R15 |
As for FP registers, the mapping is as below, XMM0
and XMM1
are reserved for temporary usage.
RISC–V register | x86–64 mapping |
---|---|
f15 | FE_XMM2 |
f14 | FE_XMM3 |
f9 | FE_XMM4 |
f13 | FE_XMM5 |
f12 | FE_XMM6 |
f10 | FE_XMM7 |
f11 | FE_XMM8 |
f1 | FE_XMM9 |
f0 | FE_XMM10 |
f3 | FE_XMM11 |
f2 | FE_XMM12 |
f31 | FE_XMM13 |
f20 | FE_XMM14 |
f24 | FE_XMM15 |
Using AVX extension or GCC Generated Code to Replace Fused Instruction Missing in x86-64 instrinsics
One could use the FMA–extension to implement the fused multiply-add instructions natively, but these instructions require AVX, which is not generally available on x86–64 hardware. As an implementation reference for these instructions, the assembly generated by GCC was used.
Taking FNMADDS
(-(rs1xrs2)-rs3
) for example, below is the code generating routine. The first part is the code generating with AVX support, and second part is without AVX support. It's quite obvious that the code generation is much complex without AVX support.
Temporary Alter Rounding Mode
Below codes in src/util/util.h
are to save/restore rounding mode. For every floating point code generation, save and restore rounding mode are necessary, and they are processed in below sequence.
src/runtime/manualCSRR.c
, to handle CSR related instructions, MXCSR related code generation is utilized
Recursive jump translation
Returning from translated guest code to the main transcode loop comes with big performance penalties. These are imposed by the first context switch, code cache lookup, and second context switch necessary for starting execution of the next basic block. To avoid these negative performance impacts, authors implemented the method of recursive translation: When the parser arrives at an unconditional jump, translation of the jump target is started recursively. That way, the jump target will always be translated before the jump itself. Because the host code address of the jump target is now already known at translate time, DBT can make the emitted host code jump to the target directly instead of returning to the transcode loop. The blocks containing jump and target are thereby chained.
Intranslate_JALR
function located in src/gen/instr/core/translate_controlflow.c
, once the chaining option is set, the routine is gone through. If the translation of next block is done, then directly load address and jump to link; otherwise, the address is calculated in relative to instruction pointer.
Retroactive block chaining
Translation in general is done lazily. This especially applies to the handling of conditional jumps, as it is nearly impossible to know at parsing time whether a branch will actually be taken or not. In cases where the translated conditional jump is not taken during execution, translating the target would cause unnecessary overhead. For that reason, authors do not recursively translate conditional jumps. If a branch is reached during translation, its two sides can only be chained if the respective target blocks have already been translated and their host code addresses are thus known. If that is not the case, the targets can instead be chained retroactively after the respective sides of the branch are first taken: following translation of the target block, the host code of the branch is modified to jump directly to the target address, which is now known, instead of returning to the translation loop. Further cache lookup and context switching are thus avoided for this side of the branch.
Taking the control flow in translating branch equal as an example, first translator generates control flow related instructions, and call translate_controlflow_set_pc2
routine.
As traslate_controlflow_set_pc2
in src/gen/instr/core/translate_controlflow.c
indicates, once code appears in cache, directly linked jump would be inserted into translated code, instead of below relative jump.
Return address stack
Dynamic jumps can not be statically chained, because their target address may vary. Still, there is potential for optimization, as the majority of dynamic jumps found in a typical program are function returns. By keeping track of function calls, it is possible to predict the return addresses. In order to do so, we use a stack that holds entries consisting of pairs containing both the guest return address and its corresponding host code address. The stack is implemented as a ring buffer to prevent over- and underflow. Calls are first detected at parsing time and have their return targets recursively translated. After that, host code will be emitted that pushes the corresponding return address pair onto the stack at every execution without having to leave guest context. Following dynamic jumps will compare their target guest-address with the entry in the top stack element. If the values match, the address pair is popped, and the target block is jumped to directly. Thus, returning to the translation loop is avoided. If the values do not match, control is handed back to the host. In this case the stack will not be changed, as it is assumed that a return corresponding to the top stack element will still follow.
Given in src/cache/stack.c
, there are push and pop operations which can be committed after initialization by utilizing r_stack
pointer. Taking push return stack for example, once the destination instructions appear in code cache, the translator generate the code which would calculate stack position first with RDX
and store RV64 address and corresponding code cache address in the entry.
}
Adapting structure data format
There are system calls like fstat and fstatat that exist both on RISC–V as well as x86–64, but use different data structure layouts in their return values. Thus, the DBT must adapt the data returned by the host to the required format prior to passing it back to the guest. Defined in src/runtime/emulateEcall.c
, authors implement how system call should be handled. For example, when fstat
is called, after calling __NR_fstat
syscall, translator needs to convert data in buffer into space pointed by simulated a1
register.
Emulation
The DBT captures the exit and exit_group calls. Passing them through would immediately terminate the DBT – an action that is undesirable as it prevents any form of clean-up or post-execution profiling and analysis to take place. Thus, the DBT uses these system calls to set a flag which stops the main loop from executing the next iteration.
The brk system call must also be entirely emulated, as it would otherwise allow the guest program to modify the data segment (program break) belonging to the DBT, thus potentially deallocating some of the critically required memory.
Below we take system call exit
as an example. First DBT sets global variable guest_exit_status
with corresponding exit code and set finalize
flag as true. The flag finalize
controls whether code translation loop should be running; thus setting it true can make guest code generation and execution stop.
Ignoring system calls
The rt_sigaction system call is ignored by the DBT. Because DBT only supports single process, any signal handler installed by the guest binary through rt_sigaction would also capture the respective signal sent to the translator. As it is impossible to distinguish the DBT from the guest program in inter-process communication, DBT must ignore this call in order to avoid undefined behaviour on signal handling. In rt_sigaction
system call handling, DBT would simply clear a0
in guest machine and do nothing.
Guarded pass-through to host.
Essentially, any system call that has the possibility to influence the state or memory of the translator needs to have respective safe-guards in place. A good example of this behaviour is the mmap system call. In any case, we must prevent a memory mapping into a memory region reserved by the translator. Mappings that do not interfere with the memory of the DBT can be passed along to the host directly.
Below we takes mmap
as an example, DBT is responsible for memory region protection and error code returning.
DBT is verified by Google Test Framework
DBT is tested by SPEC CPU 2017 benchmark suite
Evaluate different optimisation option with SPEC CPU 2017 benchmark suite
We can find that
Run gzip to simulate the real world scenario
The DBT is better than QUMU when doing some optimisation.