Last active
November 25, 2023 08:30
-
-
Save chrislattman/6fdc1dd3babb43f04c74d773157881f4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
__asm__(".globl func\n\t" // optional, makes the function visible outside of main_aarch64.c | |
"func:\n\t" // for macOS (Mach-O), change func to _func | |
"mov w0, #7\n\t" | |
"ret" | |
); | |
// the definition of func is written in assembly language above | |
extern int func(void); | |
int func2(int x, int y) | |
{ | |
int z; | |
__asm__("mov w0, %w1\n\t" | |
"mov w1, #3\n\t" | |
"mul w0, w0, w1\n\t" | |
"add w0, w0, #4\n\t" | |
"add w0, w0, %w2\n\t" | |
"mov %w0, w0" // if we returned here, a ret would be automatically generated | |
: "=r" (z) // output registers (register index starts here) | |
: "r" (x), "r" (y) // input registers | |
: "w0", "w1" // clobbered registers | |
); // stores 3x + 4 + y in z | |
return z + 5; | |
} | |
int main(void) | |
{ | |
int n = func(); | |
__asm__("mov w1, #5\n\t" | |
"mul %w0, %w0, w1" // stores n * 5 = 5n in n | |
: "=r" (n) // r means load into any available register | |
: "0" (n) // a means %rax, D means %rdi, S means %rsi | |
: "w1" // d means %rdx, c means %rcx | |
); // 0 means that input register must be the same as the 0th output register | |
printf("7*5 = %d\n", n); | |
printf("(3*%d + 4 + %d) + 5 = %d\n", 5, 8, func2(5, 8)); | |
fflush(stdout); // flush is intentional | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment