分享
Learn Assembly Language
输入“/”快速插入内容
Learn Assembly Language
飞书用户54
2024年12月21日修改
2024年3月10日创建
473
565
大多数教程,比如《深入理解计算机系统》是基于 32bit 讲解的。
gcc -m32 可得到 32bit 的汇编。
ILOC 和 risc (RISCV)
RISC 汇编,大多数以 register 寄存器为参数。
load / store 等内存操作,涉及 memory。
立即数乘法的优化
gcc 的编译优化,a + b * 9 和 a + b * 10 的汇编相差很大
代码块
C++
// c code
int simple_add(int a, int b) {
int c;
c = a + b * 9;
return c;
}
生成的汇编,对比如下
代码块
Assembly language
// a + b * 9
movl 8(%esp), %eax // b
leal (%eax,%eax,8), %eax // 9b
addl 4(%esp), %eax // a + 9b
ret
// a + b * 10
movl 8(%esp), %eax // b
movl 4(%esp), %edx // a
leal (%eax,%eax,4), %eax // 5b
leal (%edx,%eax,2), %eax // 5b * 2 + a
ret
For Loop 内的黑魔法
代码块
Assembly language
// ~0.35s
// code
int fun() {
int sum = 3;
for (int i = 0; i < N; i++) {
sum = sum + i;
}
return sum;
}
// assembly code
fun:
.LFB0:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
movl $3, -8(%rbp)
movl $0, -4(%rbp)
jmp .L2
.L3:
movl -4(%rbp), %eax
addl %eax, -8(%rbp)
addl $1, -4(%rbp)
.L2:
cmpl $99999999, -4(%rbp)
jle .L3
movl -8(%rbp), %eax
popq %rbp
.cfi_def_cfa 7, 8
ret
.cfi_endproc
50%
代码块
Assembly language
// ~0.26
// loop 多一个 +1 计算
// .L3 多了 3 行指令,反而变快了。
// code
int fun() {
int sum = 3;
for (int i = 0; i < N; i++) {
sum = sum + i + 1;
}
return sum;
}
// assembly code
fun:
.LFB0:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
movl $3, -8(%rbp)
movl $0, -4(%rbp)
jmp .L2
.L3:
movl -8(%rbp), %edx
movl -4(%rbp), %eax
addl %edx, %eax
addl $1, %eax
movl %eax, -8(%rbp)
addl $1, -4(%rbp)
.L2:
cmpl $99999999, -4(%rbp)
jle .L3
movl -8(%rbp), %eax
popq %rbp
.cfi_def_cfa 7, 8
ret
.cfi_endproc
50%