Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bradley-evans/c56dffdacec4c389fbf9b89952cfe2b2 to your computer and use it in GitHub Desktop.
Save bradley-evans/c56dffdacec4c389fbf9b89952cfe2b2 to your computer and use it in GitHub Desktop.
/*
* This is a demonstration of inline assembly for
* the RISCV platform, written in C.
*/
#include <stdio.h>
int basicsum(int op1, int op2) {
int result;
asm volatile("add %[result], %[op1], %[op2]" // AssemblerTemplate
: [result] "=r" (result) // OutputOperands
: [op1] "r" (op1), [op2] "r" (op2) // InputOperands
);
printf("\tbasicsum: %i+%i=%i\n", op1, op2, result);
return result;
}
/*
* store value in address:
* first
* then load the address into temporary register t0 / x5
* then store the value to a memory location 0 + offset (t0)
*/
void storeword(int address, int value) {
*(volatile int *)address = value;
}
int loadword(int address) {
int result = *(volatile int *)address;
printf("\tloadword: at %x, I see value %d\n", address, result);
return result;
}
int main() {
if (basicsum(5,4) == 9) {
printf("basicsum\t\t...success!\n");
}
int data = 666;
int target = 0;
int *target_addr = &target;
printf("storeword being passed value `%d` for address `%x`\n",
data, target_addr);
storeword(target_addr, data);
if (loadword(target_addr) == data) {
printf("load and store\t\t...success!\n");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment