作业3

3.3

1
2
3
4
5
6
7
movb $0xF, (ebx) # %ebx是调用者保存的信息,不能用 %ebx 作为目标地址
movl %rax, (%rap) # 指令后缀与寄存器不匹配,应为movl %eax, (%rsp) 或 movq %rax, (%rsp)
movw (%rax), 4(%rsp) # 的两个操作数不能同时为内存引用
movb %al, %sl # %sl不存在
movq %rax, $0x123 # 不能用立即数作为目标地址
movl %eax, %rdx # 应为 movl %eax, %edx
movb %si, 8(%rbp) # 指令后缀与寄存器不匹配,应为movb %sil, 8(%rbp) 或者 movw %si, 8(%rbp)

3.5

1
2
3
4
5
6
7
8
9
void decode1(long *xp, long *yp, long *zp)
{
long x = *xp;
long y = *yp;
long z = *zp;
*yp = x;
*zp = y;
*xp = z;
}

3.7

1
long t = 5 * x + 2 * y + 8 * z

3.10

1
2
3
4
5
6
7
8
long arith2(long x, long y, long z)
{
long t1 = x | y;
long t2 = t1 >> 3;
long t3 = ~t2;
long t4 = z - t3;
return t4;
}

3.15

A. 0x4003fe

B. 0x400425

C. 400543 400545

D. 0x400560

3.18

1
2
3
4
5
6
7
8
9
10
11
long test(long x, long y, long z) {
long val = x + y + z;
if (x < -3) {
if (y < z)
val = x * y;
else
val = y * z;
} else if (x > 2)
val = x * z;
return val;
}

3.21

1
2
3
4
5
6
7
8
9
10
11
long test(long x, long y) {
long val = 8 * x + 0;
if (y > 0) {
if (x < y)
val = y - x;
else
val = x & y;
} else if (y <= -2)
val = x + y;
return val;
}

3.60

A. %rdi, %esi, %rax, %rdx

B. result = 0; mask = 1;

C. mask != 0

D. mask <<= n

E. result |= (x & mask)

F.

1
2
3
4
5
6
7
8
9
long loop(long x, int n)
{
long result = 0;
long mask;
for(mask = 1; mask != 0; mask <<= n) {
result |= (x & mask)
}
return result;
}

3.61

1
2
3
long cread_alt(long *xp) {
return (!xp ? 0 : *xp);
}