说明
本文是个人学习用的非官方中英对照译文,原文:https://diveintosystems.org/book/C8-IA32/if_statements.html。
原书采用 CC BY-NC-ND 4.0 许可(禁止演绎),请勿公开传播本译文。
标为「译注」「现代更新」的内容是译者补充,不代表原书作者观点;代码与原文逐字一致,未作改动。
8.4.2. if Statements in Assembly
我们来看看 getSmallest 函数的汇编。为方便起见,这里再把函数列出来。
Let’s take a look at the
getSmallestfunction in assembly. For convenience, the function is reproduced here.
1 | int getSmallest(int x, int y) { |
从 GDB 中取出的对应汇编代码类似下面这样:
The corresponding assembly code extracted from GDB looks similar to the following:
1 | (gdb) disas getSmallest |
这是一种与我们之前见过的不同的汇编代码视图。在这里,我们能看到每条指令对应的地址,但看不到字节。注意,为了简单起见,这段汇编代码经过了少许编辑:去掉了通常属于函数建立/结束的那些指令(即 push %ebp 和 mov %esp, %ebp)以及在栈上分配空间的指令。按照惯例,GCC 把函数的第一个和第二个参数分别放在位置 %ebp+8 和 %ebp+0xc(即 %ebp+12)处。为了清楚起见,我们把这两个参数分别称为 x 和 y。
This is a different view of the assembly code than we have seen before. Here, we can see the address associated with each instruction, but not the bytes. Note that this assembly segment has been lightly edited for the sake of simplicity. The instructions that are normally part of function creation/termination (i.e.,
push %ebpandmov %esp, %ebp) and for allocating space on the stack are removed. By convention, GCC places the first and second parameters of a function at locations%ebp+8and%ebp+0xc(or%ebp+12), respectively. For the sake of clarity, we refer to these parameters asxandyrespectively.
我们来跟踪上面这段汇编代码的前几行。注意,在这个例子中我们不会明确地画出栈。我们把它留作读者的练习,鼓励你自己画一画,练习跟踪栈的技能。
Let’s trace through the first few lines of the previous assembly code snippet. Note that we will not draw out the stack explicitly in this example. We leave this as an exercise for the reader, and encourage you to practice your stack tracing skills by drawing it out yourself.
mov指令把位于地址%ebp+8处的值(第一个参数x)复制到寄存器%eax中。指令指针(%eip)被设为下一条指令的地址,即 0x08048414。
- The
movinstruction copies the value located at address%ebp+8(the first parameter,x) and places it in register%eax. The instruction pointer (%eip) is set to the address of the next instruction, or 0x08048414.
cmp指令把位置%ebp+12处的值(第二个参数y)与x进行比较,并设置相应的条件码标志寄存器。寄存器%eip前进到下一条指令的地址,即 0x08048417。
- The
cmpinstruction compares the value at location%ebp+12(the second parameter,y) toxand sets appropriate condition code flag registers. Register%eipadvances to the address of the next instruction, or 0x08048417.
- 第三行的
jle指令表示:如果x小于或等于y,下一条执行的指令位于<getSmallest+22>(即mov 0x8(%ebp), %eax),%eip应当被设为地址 0x8048421;否则,%eip被设为顺序中的下一条指令,即 0x8048419。
- The
jleinstruction on the third line indicates that ifxis less than or equal toy, the next instruction that executes is at location<getSmallest+22>(ormov 0x8(%ebp), %eax) and that%eipshould be set to address 0x8048421. Otherwise,%eipis set to the next instruction in sequence, or 0x8048419.
接下来执行哪些指令,取决于程序在第 3 行(<getSmallest+12>)是否走了分支(即是否执行了跳转)。我们先假设没有走分支。在这种情况下,%eip 被设为 0x8048419(即 <getSmallest+14>),接下来执行下面这串指令:
The next instructions to execute depend on whether the program follows the branch (i.e., executes the jump) on line 3 (
<getSmallest+12>). Let’s first suppose that the branch was not followed. In this case,%eipis set to 0x8048419 (i.e.,<getSmallest+14>) and the following sequence of instructions executes:
<getSmallest+14>处的mov 0xc(%ebp),%eax指令把y复制到寄存器%eax。寄存器%eip前进到 0x804841f。
- The
mov 0xc(%ebp),%eaxinstruction at<getSmallest+14>copiesyto register%eax. Register%eipadvances to 0x804841f.
jmp指令把寄存器%eip设为地址 0x8048427。
- The
jmpinstruction sets register%eipto address 0x8048427.
- 最后执行的是
ret指令,表示函数结束。在这种情况下,%eax中存放的是y,getSmallest返回y。
- The last instruction to execute is the
retinstruction, signifying the end of the function. In this case,%eaxcontainsy, andgetSmallestreturnsy.
现在,假设在 <getSmallest+12> 处走了分支。换句话说,jle 指令把寄存器 %eip 设为 0x8048421(即 <getSmallest+22>)。那么,接下来执行的指令是:
Now, suppose that the branch was taken at
<getSmallest+12>. In other words, thejleinstruction sets register%eipto 0x8048421 (i.e.,<getSmallest+22>). Then, the next instructions to execute are:
- 地址 0x8048421 处的
mov 0x8(%ebp),%eax指令,它把x复制到寄存器%eax。寄存器%eip前进到 0x8048427。
- The
mov 0x8(%ebp),%eaxinstruction at address 0x8048421, which copies thexto register%eax. Register%eipadvances to 0x8048427.
- 最后执行的是
ret,表示函数结束。在这种情况下,%eax中存放的是x,getSmallest返回x。
- The last instruction that executes is
ret, signifying the end of the function. In this case,%eaxcontainsx, andgetSmallestreturnsx.
于是我们可以这样为上面的汇编加上注释:
We can then annotate the preceding assembly as follows:
1 | 0x8048411 <+6>: mov 0x8(%ebp),%eax #copy x to %eax |
把它翻译回 C 代码,得到:
Translating this back to C code yields:
表 1. 把 getSmallest 翻译成 goto 形式的 C 代码和普通 C 代码
Table 1. Translating getSmallest into goto C form and C code.
goto 形式
goto Form
1 | int getSmallest(int x, int y) { |
翻译出的 C 代码
Translated C code
1 | int getSmallest(int x, int y) { |
在表 1 中,变量 smallest 对应于寄存器 %eax。如果 x 小于或等于 y,代码执行语句 smallest = x,在这个函数的 goto 形式中,它与 goto 标签 assign_x 相关联。否则,执行语句 smallest = y。goto 标签 done 用来表示应当返回 smallest 中的值。
In Table 1, the variable
smallestcorresponds to register%eax. Ifxis less than or equal toy, the code executes the statementsmallest = x, which is associated with thegotolabelassign_xin ourgotoform of this function. Otherwise, the statementsmallest = yis executed. Thegotolabeldoneis used to indicate that the value insmallestshould be returned.
注意,上面由汇编代码翻译出的 C 代码与原来的 getSmallest 函数略有不同。这些差异无关紧要;仔细检查两个函数就会发现,这两个程序在逻辑上是等价的。不过,编译器首先会把任何 if 语句转换成等价的 goto 形式,这就产生了一个略有不同但等价的版本。表 2 展示了标准的 if 语句格式及其等价的 goto 形式:
Notice that the preceding C translation of the assembly code is a bit different from the original
getSmallestfunction. These differences don’t matter; a close inspection of both functions reveals that the two programs are logically equivalent. However, the compiler first converts anyifstatement into an equivalentgotoform, which results in the slightly different, but equivalent, version. Table 2 shows the standardifstatement format and its equivalentgotoform:
表 2. 标准的 if 语句格式及其等价的 goto 形式
Table 2. Standard if-statement format and its equivalent goto form.
C 的 if 语句
C if-statement
1 | if (condition) { |
编译器的等价 goto 形式
Compiler’s equivalent goto form
1 | if (!condition) { |
编译器在把代码翻译成汇编时,指定的是条件为真时跳转。对比一下 if 语句的结构,它是在条件不为真时发生「跳转」(跳到 else)。goto 形式体现了这一逻辑上的差别。
Compilers translating code into assembly designate a jump when a condition is true. Contrast this behavior with the structure of an
ifstatement, where a “jump” (to theelse) occurs when conditions are not true. Thegotoform captures this difference in logic.
考虑 getSmallest 函数原来的 goto 翻译,可以看出:
Considering the original
gototranslation of thegetSmallestfunction, we can see that:
x <= y对应于!condition。
x <= ycorresponds to!condition.
smallest = x是else_statement。
smallest = xis theelse_statement.
smallest = y这一行是then_statement。
- The line
smallest = yis thethen_statement.
- 函数的最后一行是
return smallest。
- The last line in the function is
return smallest.
按照上面的注解改写原来的函数,得到:
Rewriting the original version of the function with the preceding annotations yields:
1 | int getSmallest(int x, int y) { |
这个版本与原来的 getSmallest 函数完全相同。记住,在 C 语言中用不同方式编写的函数,可能会被翻译成同一组汇编指令。
This version is identical to the original
getSmallestfunction. Keep in mind that a function written in different ways in the C language can translate to the same set of assembly instructions.
cmov 指令
The cmov Instructions
我们要介绍的最后一组条件指令是条件传送(conditional move,cmov)指令。cmp、test 和 jmp 指令在程序中实现的是有条件的控制转移。换句话说,程序的执行会向多个方向分支。这对于优化代码来说可能非常麻烦,因为这些分支的代价很高。
The last set of conditional instructions we cover are conditional move (
cmov) instructions. Thecmp,test, andjmpinstructions implement a conditional transfer of control in a program. In other words, the execution of the program branches in many directions. This can be very problematic for optimizing code, because these branches are very expensive.
与之不同,cmov 指令实现的是有条件的数据传送。换句话说,条件的 then 语句和 else 语句都会被执行,然后根据条件的结果,把数据放到相应的寄存器中。
In contrast, the
cmovinstruction implements a conditional transfer of data. In other words, both thethen-statement` andelse-statement` of the conditional are executed, and the data is placed in the appropriate register based on the result of the condition.
使用 C 的三元表达式(ternary expression)常常会使编译器生成 cmov 指令来代替跳转。对于标准的 if-then-else 语句,三元表达式的形式是:
The use of C’s ternary expression often results in the compiler generating a
cmovinstruction in place of jumps. For the standard if-then-else statement, the ternary expression has the form:
1 | result = (condition) ? then_statement : else_statement; |
我们用这种格式把 getSmallest 函数改写成三元表达式。记住,这个新版本函数的行为与原来的 getSmallest 函数完全相同:
Let’s use this format to rewrite the
getSmallestfunction as a ternary expression. Keep in mind that this new version of the function behaves exactly as the originalgetSmallestfunction:
1 | int getSmallest_cmov(int x, int y) { |
这看起来也许不是什么大的改动,但我们来看看生成的汇编。回想一下,第一个和第二个参数(x 和 y)分别存放在栈地址 %ebp+0x8 和 %ebp+0xc 处。
Although this may not seem like a big change, let’s look at the resulting assembly. Recall that the first and second parameters (
xandy) are stored at stack addresses%ebp+0x8and%ebp+0xc, respectively.
1 | 0x08048441 <+0>: push %ebp #save ebp |
这段汇编代码中没有跳转。比较了 x 和 y 之后,只有当 x 小于或等于 y 时,x 才会被移入返回寄存器。与跳转指令一样,cmov 指令的后缀表示进行条件传送的条件。表 3 列出了条件传送指令的集合。
This assembly code has no jumps. After the comparison of
xandy,xmoves into the return register only ifxis less than or equal toy. Like the jump instructions, the suffix of thecmovinstructions indicates the condition on which the conditional move occurs. Table 3 lists the set of conditional move instructions.
表 3. cmov 指令
Table 3. The cmov Instructions.
| 有符号 | 无符号 | 说明 |
|---|---|---|
cmove (cmovz) |
相等(==)时传送 | |
cmovne (cmovnz) |
不相等(!=)时传送 | |
cmovs |
为负时传送 | |
cmovns |
非负时传送 | |
cmovg (cmovnle) |
cmova (cmovnbe) |
大于(>)时传送 |
cmovge (cmovnl) |
cmovae (cmovnb) |
大于等于(>=)时传送 |
cmovl (cmovnge) |
cmovb (cmovnae) |
小于(<)时传送 |
cmovle (cmovng) |
cmovbe (cmovna) |
小于等于(<=)时传送 |
Signed Unsigned Description cmove(cmovz)move if equal (==) cmovne(cmovnz)move if not equal (!=) cmovsmove if negative cmovnsmove if non-negative cmovg(cmovnle)cmova(cmovnbe)move if greater (>) cmovge(cmovnl)cmovae(cmovnb)move if greater than or equal (>=) cmovl(cmovnge)cmovb(cmovnae)move if less (<) cmovle(cmovng)cmovbe(cmovna)move if less than or equal (<=)
编译器在把跳转指令转换成 cmov 指令时非常谨慎,尤其是在涉及副作用和指针值的情况下。表 4 展示了 incrementX 函数的两种等价写法:
The compiler is very cautious about converting jump instructions into
cmovinstructions, especially in cases where side effects and pointer values are involved. Table 4 shows two equivalent ways of writing a function,incrementX:
表 4. 两个试图让整数 x 的值加一的函数
Table 4. Two functions that attempt to increment the value of integer x.
C 代码
C code
1 | int incrementX(int * x) { |
C 三元形式
C ternary form
1 | int incrementX2(int * x){ |
每个函数都以一个指向整数的指针作为输入,并检查它是否为 NULL。如果 x 不为 NULL,函数让 x 所指向的值加一并返回它;否则,函数返回值 1。
Each function takes a pointer to an integer as input and checks whether it is
NULL. Ifxis notNULL, the function increments and returns the dereferenced value ofx. Otherwise, the function returns the value 1.
译注
与第 7 章的译注相同:(*x)++ 是后置自增,函数返回的是加一之前的值。下面汇编中 mov (%eax),%eax 取出旧值作为返回值,lea 0x1(%eax),%ecx 算出新值写回 *x。
人们很容易以为 incrementX2 会使用 cmov 指令,因为它用的是三元表达式。然而,两个函数生成的汇编代码完全相同:
It is tempting to think that
incrementX2uses acmovinstruction because it uses a ternary expression. However, both functions yield the exact same assembly code:
1 | 0x80484cf <+0>: push %ebp |
回想一下,cmov 指令会执行条件的两个分支。换句话说,无论如何都会对 x 解引用。考虑 x 是空指针的情况。回想一下,对空指针解引用会在代码中引发空指针异常,导致段错误。为了杜绝这种情况发生的任何可能,编译器选择了稳妥的做法,使用跳转。
Recall that the
cmovinstruction executes both branches of the conditional. In other words,xgets dereferenced no matter what. Consider the case wherexis a null pointer. Recall that dereferencing a null pointer leads to a null pointer exception in the code, causing a segmentation fault. To prevent any chance of this happening, the compiler takes the safe road and uses jumps.