Option 的 Rust 组装<i32>

问题描述 投票:0回答:1

此代码是用

https://gcc.godbolt.org/z/jqEjasPTW
中的 -C opt-level=3

编译的
#[no_mangle]
pub fn match1(num: i32) -> i32 {
   if num == 10 {99} else {11}
}

#[no_mangle]
pub fn match2(num: Option<i32>) -> i32 {
    match num {
        Some(a) => a,
        _ => 11
    }
}
 

产生这个汇编代码:

match1:
        cmp     edi, 10
        mov     ecx, 99
        mov     eax, 11
        cmove   eax, ecx
        ret

match2:
        cmp     edi, 1
        mov     eax, 11
        cmove   eax, esi
        ret

为什么在 match2 中将寄存器 edi 与 1 进行比较?

assembly rust godbolt
1个回答
1
投票

这里没有汇编专家,但我想这就是那里发生的事情(以伪代码形式):

var eax = 11; // assume it's None

if (edi == 1) { // it's Some
  eax = esi; // esi contains the "content" of Some, that is `a`
}

return eax;
  

所以

edi
1
的比较基本上是为了检查它是否是
Some
。 当然
edi
esi
是函数参数,分别包含指示是否为
Some
的值和
Some
的值。

© www.soinside.com 2019 - 2024. All rights reserved.