5.汇编基础

基本格式

语法

Label Symbolic Labeling of an assembler address
mnemonic Symbolic description of the operation
operands 操作数 Contains of variables or addresses if necessary
comments ;表示,Optional Field

地址

Endianess (Bit Order)

  • The ARM processor is little endian by default; and can be programmed to operate as big endian

Wtite Assembly for ARM

回顾

ISA (Istruction Set Architecture)

  1. 信息的获取存储
  • Memory

  • Register

  • I/O Devices

  1. 信息的处理
  • Assembly-Language Instructions

  • Hardware Process Actions

RISC

  1. Load

  1. Store

  1. Data Path & Control Unit

  1. Instruction Pipelines

重要单元结构

Arm Register File

  • PC 存储下一条指令的地址

Cortex-M Memory Map (内存图)

  1. 32位支持$2^{32} = 2^{30} \times 2^2 =4G$ 内存

  2. Code、Data、I/O 共用内存

  3. 数据类型: Bytes, words, halfwords

  4. 内存地址类型: Bytes

  • Vendor Specifc: 针对某个厂商的

Data Path & Control Unit

Instructions

  1. Arithmatic、Logic、Comparison Operation

  2. Data Movement between Registers

Registers

  1. Saved Register: R4-R11, hold variables

  2. Temporary Register: R0-R3, R12, hold intermediate values

指令 助记符 标志位 标签

ARM Cortex-M的汇编指令

MOV 寄存器之间移动
MVN MOVE and NOT, 取反并移动
LDR LOAD, 从内存(操作数2)中加载到寄存器(操作数1)中
STR STORE, 从寄存器(操作数1)中存储到内存(操作数2)中
[a,b] 地址a+b
ADR(伪指令) Address, 让寄存器指向后面的地址
ADD 相加
ADC 带进位的加法运算
SUB 相减
SBC 带进位的减法运算
AND 按位与
BIC(Bit Clean) 按位与非,将第一个操作数中对应的第二个操作数中为1的位清零
ORR 按位或
LSL(Logical Shift Left) 左移
LSR 右移
MUL 乘法($32bit \times 32bit = 32bit$),结果没有影响
CMP 比较
EOR Exclusive OR, 异或

ARM ALU*

Conditional Flag (CNVZ)

  1. 标识位解释
N Negative, 负标志位
Z Zero, 零标志位(若相等,零标志位=1)
C Carry, 进位标志位
V Overflow, 溢出标志位
  1. 助记符
NE 不等于
EQ 等于
MI Morse Code International, 当标志位N=1时执行指令
  1. 示例(Conditional Opcode)
1
2
CMP R1 R2
SUBNE R3, R5, R8 ; 只有当R1 != R2 时才能执行SUB

Branching

1
2
3
4
5
6
MOV R2 #17
B TARGET
ORR R1, R4, #14

TARGET
    SUB R1, R1, #78 ; TARGET就是Label

用汇编写C

  1. MAX函数
1
2
3
4
5
6
7
8
int main(){
    int max = 0, a = 2, b = 3;
    if (a < b)
        max = b;
    else
        max = a;
    return max;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
MAIN
    MOV R1 #2
    MOV R2 #3
    CMP R1 R2
    BLT LOWER

    MOV R0 R1
    B END
LOWER
    MOV R0 R2
    B END
END
    BX LR
  1. 循环
1
2
3
4
5
6
int main(){
    int a = 0;
    while (a < 4)
        a += 1;
    return a;
}
1
2
3
4
5
6
7
8
9
MAIN
    MOV R0 #0
WHILE
    CMP R0 #4
    BEQ END
    ADD R0 #1
    B WHILE
END
    BX LR
  1. 指数运算
1
2
3
4
5
6
7
int pow = 1;
int x = 0;

while (pow !=128) {
    pow*=2;
    x+=1;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
R0 = pow, R1 = x
MOV R0 #1
MOV R1 #0

WHILE
    CMP R0 #128
    BEQ DONE
    LSL R0 #1
    ADD R1 #1

    B WHILE; 重复循环
DONE

附录

#代表立即数

Licensed under CC BY-NC-SA 4.0
comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy