编译器会将这些值存储在多个寄存器中,并在需要时使用多条指令对这些值进行算术运算。大多数 ISA 都有一个 add-with-carry 指令,例如 x86's adc,这使得执行扩展精度整数加/减相当有效。
例如,给定
fn main() {
let a = 42u128;
let b = a + 1337;
}
编译器在为 x86-64 编译而不进行优化时会生成以下内容:
(@PeterCordes 添加的 cmets)
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
您可以看到42 的值存储在rax 和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 则跳转)可以正常工作。
启用优化后,Rust 编译器不会检查溢出,因此 + 的工作方式类似于 .wrapping_add()。