Assembly Language for Beginners

(nextflipdebug2) #1
1.9. SCANF()
The new instructions here areCMPandBEQ^80.

CMPis analogous to the x86 instruction with the same name, it subtracts one of the arguments from the
other and updates the conditional flags if needed.

BEQjumps to another address if the operands were equal to each other, or, if the result of the last
computation has been 0, or if the Z flag is 1. It behaves asJZin x86.

Everything else is simple: the execution flow forks in two branches, then the branches converge at the
point where 0 is written into theR0as a function return value, and then the function ends.

ARM64

Listing 1.84: Non-optimizing GCC 4.9.1 ARM64
1 .LC0:
2 .string "Enter X:"
3 .LC1:
4 .string "%d"
5 .LC2:
6 .string "You entered %d...\n"
7 .LC3:
8 .string "What you entered? Huh?"
9 f6:
10 ; save FP and LR in stack frame:
11 stp x29, x30, [sp, -32]!
12 ; set stack frame (FP=SP)
13 add x29, sp, 0
14 ; load pointer to the "Enter X:" string:
15 adrp x0, .LC0
16 add x0, x0, :lo12:.LC0
17 bl puts
18 ; load pointer to the "%d" string:
19 adrp x0, .LC1
20 add x0, x0, :lo12:.LC1
21 ; calculate address of x variable in the local stack
22 add x1, x29, 28
23 bl __isoc99_scanf
24 ; scanf() returned result in W0.
25 ; check it:
26 cmp w0, 1
27 ; BNE is Branch if Not Equal
28 ; so if W0<>0, jump to L2 will be occurred
29 bne .L2
30 ; at this moment W0=1, meaning no error
31 ; load x value from the local stack
32 ldr w1, [x29,28]
33 ; load pointer to the "You entered %d...\n" string:
34 adrp x0, .LC2
35 add x0, x0, :lo12:.LC2
36 bl printf
37 ; skip the code, which print the "What you entered? Huh?" string:
38 b .L3
39 .L2:
40 ; load pointer to the "What you entered? Huh?" string:
41 adrp x0, .LC3
42 add x0, x0, :lo12:.LC3
43 bl puts
44 .L3:
45 ; return 0
46 mov w0, 0
47 ; restore FP and LR:
48 ldp x29, x30, [sp], 32
49 ret


Code flow in this case forks with the use ofCMP/BNE(Branch if Not Equal) instructions pair.

(^80) (PowerPC, ARM) Branch if Equal

Free download pdf