Programming

Rust의 128 비트 정수 'i128'은 64 비트 시스템에서 어떻게 작동합니까?

procodes 2020. 7. 23. 21:06
반응형

Rust의 128 비트 정수 'i128'은 64 비트 시스템에서 어떻게 작동합니까?


Rust는 128 비트 정수를 가지며, 데이터 타입으로 표시됩니다 i128( u128부호없는 정수).

let a: i128 = 170141183460469231731687303715884105727;

Rust는 이러한 i128값을 64 비트 시스템에서 어떻게 작동합니까 ? 예를 들어 어떻게 이것들을 산술합니까?

내가 아는 한, 값은 x86-64 CPU의 하나의 레지스터에 맞지 않기 때문에 컴파일러는 어떻게 든 하나의 i128값에 2 개의 레지스터를 사용 합니까? 아니면 그것들을 대신하기 위해 일종의 큰 정수 구조체를 사용하고 있습니까?


모든 Rust의 정수 유형은 LLVM integers 로 컴파일됩니다 . LLVM 추상 시스템은 1에서 2 ^ 23-1 사이의 모든 비트 폭의 정수를 허용합니다. * LLVM 명령어는 일반적으로 모든 크기의 정수에서 작동합니다.

분명히 838307 비트의 아키텍처는 많지 않기 때문에 코드가 네이티브 머신 코드로 컴파일 될 때 LLVM은이를 구현하는 방법을 결정해야합니다. 추상 명령어의 의미는 addLLVM 자체에 의해 정의됩니다. 일반적으로, 네이티브 코드와 동일한 단일 명령어를 갖는 추상 명령어는 해당 네이티브 명령어로 컴파일되며, 그렇지 않은 명령어는 여러 네이티브 명령어로 에뮬레이션되지 않습니다. mcarton의 답변 은 LLVM이 기본 명령어와 에뮬레이트 된 명령어를 모두 컴파일하는 방법을 보여줍니다.

(이것은 네이티브 머신이 지원할 수있는 것보다 큰 정수뿐만 아니라 더 작은 정수에도 적용됩니다. 예를 들어, 현대 아키텍처는 네이티브 8 비트 산술을 지원하지 않을 수 있으므로 add두 개의 명령어 i8가 에뮬레이트 될 수 있습니다 더 넓은 명령으로 여분의 비트는 버려집니다.)

컴파일러는 어떻게 든 하나의 i128값에 2 개의 레지스터를 사용합니까 ? 아니면 그것들을 표현하기 위해 어떤 종류의 큰 정수 구조체를 사용하고 있습니까?

LLVM IR 수준에서 답은 다음 i128과 같습니다 . 다른 모든 단일 값 유형 과 마찬가지로 단일 레지스터에 맞지 않습니다 . 반면에 일단 머신 코드로 변환 된 후에는 구조체가 정수처럼 레지스터로 분해 될 수 있기 때문에 둘 사이에는 실제로 차이가 없습니다. 그러나 산술을 할 때 LLVM이 모든 것을 두 개의 레지스터에로드하는 것이 안전합니다.


그러나 모든 LLVM 백엔드가 동일한 것은 아닙니다. 이 답변은 x86-64와 관련이 있습니다. 128보다 큰 크기와 2의 비 제곱에 대한 백엔드 지원은 드문 것으로 이해합니다 (Russt가 8, 16, 32, 64 및 128 비트 정수만 노출하는 이유를 부분적으로 설명 할 수 있음). Reddit의 est31에 따르면 rustc은 기본적으로 지원하지 않는 백엔드를 대상으로 할 때 소프트웨어에서 128 비트 정수를 구현합니다.


컴파일러는이를 여러 레지스터에 저장하고 필요한 경우 여러 명령어를 사용하여 해당 값을 산술합니다. 대부분의 ISA에는 x86adc 과 같은 캐리 추가 명령 이있어 확장 정밀도 정수 추가 / 서브를 수행하는 것이 상당히 효율적입니다.

예를 들어, 주어진

fn main() {
    let a = 42u128;
    let b = a + 1337;
}

컴파일러는 최적화없이 x86-64를 컴파일 할 때 다음을 생성합니다.
(@PeterCordes가 추가 한 주석)

playground::main:
    sub rsp, 56
    mov qword ptr [rsp + 32], 0
    mov qword ptr [rsp + 24], 42         # store 128-bit 0:42 on the stack
                                         # little-endian = low half at lower address

    mov rax, qword ptr [rsp + 24]
    mov rcx, qword ptr [rsp + 32]        # reload it to registers

    add rax, 1337                        # add 1337 to the low half
    adc rcx, 0                           # propagate carry to the high half. 1337u128 >> 64 = 0

    setb    dl                           # save carry-out (setb is an alias for setc)
    mov rsi, rax
    test    dl, 1                        # check carry-out (to detect overflow)
    mov qword ptr [rsp + 16], rax        # store the low half result
    mov qword ptr [rsp + 8], rsi         # store another copy of the low half
    mov qword ptr [rsp], rcx             # store the high half
                             # These are temporary copies of the halves; probably the high half at lower address isn't intentional
    jne .LBB8_2                       # jump if 128-bit add overflowed (to another not-shown block of code after the ret, I think)

    mov rax, qword ptr [rsp + 16]
    mov qword ptr [rsp + 40], rax     # copy low half to RSP+40
    mov rcx, qword ptr [rsp]
    mov qword ptr [rsp + 48], rcx     # copy high half to RSP+48
                  # This is the actual b, in normal little-endian order, forming a u128 at RSP+40
    add rsp, 56
    ret                               # with retval in EAX/RAX = low half result

42rax및에 저장되어 있음을 확인할 수 있습니다 rcx.

(편집자 주 : x86-64 C 호출 규칙은 RDX : RAX에서 128 비트 정수를 main반환 하지만 값을 전혀 반환하지는 않습니다. 모든 중복 복사는 순전히 최적화 비활성화에서 비롯되며 Rust는 실제로 디버그 오버플로를 검사합니다. 양식.)

비교를 위해 다음은 x86-64의 Rust 64 비트 정수에 대한 asm입니다. 여기에는 캐리 추가 기능이 필요하지 않으며 각 값에 대해 단일 레지스터 또는 스택 슬롯 만 있습니다.

playground::main:
    sub rsp, 24
    mov qword ptr [rsp + 8], 42           # store
    mov rax, qword ptr [rsp + 8]          # reload
    add rax, 1337                         # add
    setb    cl
    test    cl, 1                         # check for carry-out (overflow)
    mov qword ptr [rsp], rax              # store the result
    jne .LBB8_2                           # branch on non-zero carry-out

    mov rax, qword ptr [rsp]              # reload the result
    mov qword ptr [rsp + 16], rax         # and copy it (to b)
    add rsp, 24
    ret

.LBB8_2:
    call panic function because of integer overflow

setb / 테스트는 여전히 완전히 중복 jc됩니다 (CF = 1이면 점프).

With optimization enabled, the Rust compiler doesn't check for overflow so + works like .wrapping_add().


Yes, just the same way as 64-bit integers on 32-bit machines were handled, or 32-bit integers on 16-bit machines, or even 16- and 32-bit integers on 8-bit machines (still applicable to microcontrollers!). Yes, you store the number in two registers, or memory locations, or whatever (it doesn't really matter). Addition and subtraction are trivial, taking two instructions and using the carry flag. Multiplication requires three multiplies and some additions (it's common for 64-bit chips to already have a 64x64->128 multiply operation that outputs to two registers). Division... requires a subroutine and is quite slow (except in some cases where division by a constant can be transformed into a shift or a multiply), but it still works. Bitwise and/or/xor merely have to be done on the top and bottom halves separately. Shifts can be accomplished with rotation and masking. And that pretty much covers things.


To provide perhaps a clearer example, on x86_64, compiled with the -O flag, the function

pub fn leet(a : i128) -> i128 {
    a + 1337
}

compiles to

example::leet:
  mov rdx, rsi
  mov rax, rdi
  add rax, 1337
  adc rdx, 0
  ret

(My original post had u128 rather than the i128 you asked about. The function compiles the same code either way, a good demonstration that signed and unsigned addition are the same on a modern CPU.)

The other listing produced unoptimized code. It’s safe to step through in a debugger, because it makes sure you can put a breakpoint anywhere and inspect the state of any variable at any line of the program. It’s slower and harder to read. The optimized version is much closer to the code that will actually run in production.

The parameter a of this function is passed in a pair of 64-bit registers, rsi:rdi. The result is returned in another pair of registers, rdx:rax. The first two lines of code initialize the sum to a.

The third line adds 1337 to the low word of the input. If this overflows, it carries the 1 in the CPU’s carry flag. The fourth line adds zero to the high word of the input—plus the 1 if it got carried.

You can think of this as simple addition of a one-digit number to a two-digit number

  a  b
+ 0  7
______
 

but in base 18,446,744,073,709,551,616. You’re still adding the lowest “digit” first, possibly carrying a 1 to the next column, then adding the next digit plus the carry. Subtraction is very similar.

Multiplication must use the identity (2⁶⁴a + b)(2⁶⁴c + d) = 2¹²⁸ac + 2⁶⁴(ad+bc) + bd, where each of these multiplications returns the upper half of the product in one register and the lower half of the product in another. Some of those terms will be dropped, because bits above the 128th don’t fit into a u128 and are discarded. Even so, this takes a number of machine instructions. Division also takes several steps. For a signed value, multiplication and division would additionally need to convert the signs of the operands and the result. Those operations are not very efficient at all.

On other architectures, it gets easier or harder. RISC-V defines a 128-bit instruction-set extension, although to my knowledge no one has implemented it in silicon. Without this extension, the RISC-V architecture manual recommends a conditional branch: addi t0, t1, +imm; blt t0, t1, overflow

SPARC has control codes like the control flags of x86, but you have to use a special instruction, add,cc, to set them. MIPS, on the other hand, requires you to check whether the sum of two unsigned integers is strictly less than one of the operands. If so, the addition overflowed. At least you’re able to set another register to the value of the carry bit without a conditional branch.

참고URL : https://stackoverflow.com/questions/57340308/how-does-rusts-128-bit-integer-i128-work-on-a-64-bit-system

반응형